Reputation: 97
I'm a beginner in Python, I'm doing an API request and receiving the following JSON:
{
'data': {
'timelines': [{
'timestep': 'current',
'startTime': '2021-05-29T14:46:00Z',
'endTime': '2021-05-29T14:46:00Z',
'intervals': [{
'startTime': '2021-05-29T14:46:00Z',
'values': {
'temperature': 21.92
}
}]
}]
}
}
I want to print the temperature and I read that I have to parse the JSON in order to use the date inside of it so I did this:
response = requests.request("GET", url, headers=headers, params=querystring)
jsonunparsed = response.json()
parsed = json.loads(jsonunparsed)
I suppose to have a dictionary now but when I run this
print(parsed)
I have only one Key which is 'data'
Finally I decide to comment all the above and running the below code I'm able to print the temperature
response_json = response.json()
print(response_json['data']['timelines'][0]['intervals'][0]['values']['temperature'])
So my questions are, isn't mandatory to parse the json? Why is working my second option? when shall I parse the json using loads() and when shall I operate directly with it? What are the pros and cons of each option? How could I retrieve the temperature with the parsed json?
Thanks
Upvotes: 1
Views: 829
Reputation: 736
response.json()
is already a parsed JSON - requests
does it for you, so there is no need to use json.loads()
You use json.loads()
when dealing with a string, like:
unparsedJSON = "{'key': 'value'}"
parsedJSON = json.loads(unparsedJSON)
This would convert the string (unparsedJSON
) into a dictionary.
If you were to use response.text
instead of response.json()
, then you could use json.loads()
, but since requests can already do it for you, there's no reason to do this. If you were to do it however, it would look like this:
unparsedJSON = response.text
parsedJSON = json.loads(unparsedJSON)
Upvotes: 2
Reputation: 63
response.json() already converts(or parses) the response object into JSON's equivalent Python object(Dictionary) so you don't need json.loads(jsonunparsed) call, provided it is a valid JSON. Else it will throw exception.
jsonunparsed = response.json()
parsed = json.loads(jsonunparsed)
So you can write it this way too
jsonparsed = response.json()
print(jsonparsed['data']['timelines'][0]['intervals'][0]['values']['temperature'])
Upvotes: 0