1

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

1
  • response.json() does the parsing for you. Commented May 29, 2021 at 22:17

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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'])
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.