Home > Enterprise >  How to Extract Particular Data From JSON Python
How to Extract Particular Data From JSON Python

Time:10-06

I have this json: https://i.imgur.com/12w7Kx1.png

how to parse all the names, inside book, i can get one by:

import requests
url = "https://www.storytel.com/api/search.action?q=white feather"
r = requests.get(url)
cont = r.json()
# print(cont)
print(cont['books'][0]['book']['name'])

but how can i get all the "name"? i have tried this but did not work:

data = cont['books']

for book in data:
    print(cont['book']['name'])

error is:

Traceback (most recent call last): File "testing.py", line 12, in module> print(cont['book']['name']) KeyError: 'book' 

CodePudding user response:

You aren't using the variable (as opposed to the string) book in your loop.

CodePudding user response:

You are referring to the incorrect variable inside the loop, instead of cont you should refer book instance.

import requests
import json

url = "https://www.storytel.com/api/search.action?q=white feather"
r = requests.get(url)
cont = r.json()
data = cont['books']
for book in data:
    print(book['book']['name']) # here instead of pointing to Book instance, you are pointing to cont dictionary which is creating the issue

Output :

The White Feather
The White Feather
Little White Feather
The White Feather Murders
The White Feather Killer
The White Feather Hex
  • Related