+ 8

How do you output every item from a nested json response from an API in python?

{ "id": 2, "name": "Morty Smith", "status": "Alive", "species": "Human", "type": "", "gender": "Male", "origin": { "name": "Earth", "url": "https://rickandmortyapi.com/api/location/1" }, "location": { "name": "Earth", "url": "https://rickandmortyapi.com/api/location/20" }, "image": "https://rickandmortyapi.com/api/character/avatar/2.jpeg", "episode": [ "https://rickandmortyapi.com/api/episode/1", "https://rickandmortyapi.com/api/episode/2", // ... ], "url": "https://rickandmortyapi.com/api/character/2", "created": "2017-11-04T18:50:21.651Z" }

13th Oct 2018, 7:34 AM
0x6176696c61
0x6176696c61 - avatar
2 Respostas
+ 9
You can use this: Assuming that response is in the format you specified above for key, value in response.items(): print("%s: %s" % (key, value)) or if you want to go deeper recursively: def rec_print(data): for key, value in data.items(): if isinstance(value, dict): rec_print(value) else: print("%s: %s" % (key, value)) rec_print(response)
13th Oct 2018, 8:29 AM
Burey
Burey - avatar
+ 4
# PrettyPrinter from pprint import pprint import json _="""{ your json (remove the , //... in "episode", that won't parse) } """ # load string, pretty print the object pprint(json.loads(_)) If you assign the output from loads() to a variable you can also iterate using Burey's code.
13th Oct 2018, 3:20 PM
Kirk Schafer
Kirk Schafer - avatar