AlphaQ AlphaQ - 12 days ago 5
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.

Update



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)


Error:

File "test.py", 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
obj[0]["id"]
outputs
2
. Is there any way I can get the expected output without accessing the keys explicitly?

Answer

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)