Work JSON concrete values of an API

1

After making a request to an API I get an answer like the one shown below.

{
  "mensaje": "success", 
  "respuesta": [
    {
      "tiempo": 594, 
      "total": 1543419350
    }, 
    {
      "tiempo": 627, 
      "total": 1543425114
    }
  ]
}

This is seen in its entirety using .content

print "Cuerpo de la respuesta:\n",response.content

And you can simply see 'answer' by

decoded = json.loads(response.content)
print decoded['respuesta']

Something like this remains:

[{u'tiempo': 594, u'total': 1543419350}, {u'tiempo': 627, u'total': 1543425114}]

But how can I do to save all the values of 'total' (in this case 2) in a list so I can work with them? In other words, how do I get there, without the rest?

Cheers!

    
asked by NEA 28.11.2018 в 11:01
source

1 answer

1

Once you have converted the JSON to a native Python type, you can use the typical tools of this language to access the information.

In your case, the JSON has become a dictionary, one of whose keys is 'respuesta' and what is in that key is a list, so you can perfectly iterate over it, either in a loop for or through a list comprehension . Each item in that list is in turn a dictionary, and what interests you in that dictionary is the total key. Therefore, the following expression would extract only the numeric data associated with that key:

tiempos = [ d['total'] for d in decoded['respuesta'] ]

The variable d is taking values from the list decoded['respuesta'] . Each value is a dictionary from which we extract d['total'] . By enclosing the entire expression in brackets, we create a list comprehension , which causes python to execute that internal loop and build a list of the results. That is, you get at the end the list of numbers you were looking for.

>>> print(tiempos)
[1543419350, 1543425114]

A detail, if for the request to the API you used the library requests , you can directly use decoded = response.json() , without needing to use json.loads() .

    
answered by 28.11.2018 / 13:07
source