Print specified JSON value

Asked

Viewed 109 times

2

I am creating an application whose one of the returns comes from an API (return in JSON), and I need to collect the value of the key 'text' but when I return this way:

    data = json.dumps(response)
    data = json.loads(data)
    print(data["output"][0]["text"])

However, a traceback occurs:

    Traceback (most recent call last):
  File "Codigo-Fonte\app.py", line 21, in <module>
    print(data["output"][0]["text"])
  KeyError: 0

Can anyone tell me where the mistake might be?

Follow the return of JSON:

{
  "intents": [
    {
      "intent": "teste",
      "confidence": 0.27630176939283047
    }
  ],
  "entities": [],
  "input": {
    "text": "teste"
  },
  "output": {
    "generic": [
      {
        "response_type": "text",
        "text": "Opa esse e o retorno do gteste =D"
      }
    ],
    "text": [
      "Opa esse e o retorno do gteste =D"
    ],
    "nodes_visited": [
      "node_1_1547121892240"
    ],
    "log_messages": []
  },
  "context": {
    "conversation_id": "fe1bb066-d16b-4001-9074-000a2eeb428f",
    "system": {
      "initialized": true,
      "dialog_stack": [
        {
          "dialog_node": "root"
        }
      ],
      "dialog_turn_counter": 1,
      "dialog_request_counter": 1,
      "_node_output_map": {
        "node_1_1547121892240": {
          "0": [
            0
          ]
        }
      },
      "branch_exited": true,
      "branch_exited_reason": "completed"
    }
  }
}

1 answer

1

You just mapped the wrong print print(data["output"][0]["text"]), the correct would be print(data['output']['text'][0]).

Or print(data['output']['text']) if you want to print all the contents of data['output']['text']

Get a working look here https://repl.it/repls/HungryHummingPostgres

Browser other questions tagged

You are not signed in. Login or sign up in order to post.