AlphaQ AlphaQ - 4 months ago 28
JSON Question

JSON parsing in Python without explicitly accessing keys

JSON data:

"id": 2,
"name": "An ice sculpture",
"price": 12.50,

"id": 3,
"name": "A blue mouse",
"price": 25.50,

Expected output:

id - 2
name - An ice sculpture
price - 12.50

Something similar for id = 3.


What I did so far:

content = urllib.request.urlopen(url).read().decode('utf-8')
content = content.replace("//" , "").strip() #there is a // at the beginning
obj = json.loads(content)
for obj in content:
for key, value in obj.items():
print (obj.key, obj.value)


File "", line 22, in get
for key, value in obj.items():
AttributeError: 'str' object has no attribute 'items'

I've seen mostly data is accessed directly using the attribute keys like
. Is there any way I can get the expected output without accessing the keys explicitly?


You have a list of dictionaries. Your code would work, as long as you iterate through the outer list:

for obj in my_json_data:
    for key, value in obj.items():
         print (obj.key, obj.value)