[Solved] Taking 1 specific item out of JSON response using Python


Consider a simplified example where your line of code

>>> response=conn.getresponse()

has retrieved the response from the server and saved it as an HTTPResponse object, and when you .read() the response you see a JSON string like this

>>> responseData = response.read().decode('utf-8')
>>> responseData
'{"day": "Thursday", "id": 3720348749}'

You can use Python’s built-in JSON decoder to convert that into a Dictionary object named items

>>> import json
>>> items = json.loads(responseData)

Now you can extract the id value by referring to the Dictionary entry whose key is ‘id’

>>> idValue = items['id']
>>> print(idValue)
3720348749

If you run the same code tomorrow and the response object that is returned contains

>>> responseData = response.read().decode('utf-8')
>>> responseData
'{"day": "Friday", "id": 4567890123}'

then the same set of steps will extract the new value for id

>>> import json
>>> items = json.loads(responseData)
>>> idValue = items['id']
>>> print(idValue)
4567890123

Update

If your actual JSON data contains nested elements then you may need to use several “key” values to identify the item you want. For example if the “id” you want to retrieve is actually

result
    job
        id

i.e., the JSON looks like

'{"result": {"job": {"id": 12345678}}}'

then you will need to use

idValue = items['result']['job']['id']

12

solved Taking 1 specific item out of JSON response using Python