I've already checked here and here.
I have the following json which has no root element and I want to loop through each item in objects
and print the value for object_code
:
{
"count": 3,
"objects": [
{
"object_code": "HN1059"
},
{
"object_code": "HN1060"
},
{
"object_code": "VO1013"
}
]
}
I tried:
json='{"count": 3,"objects": [{"object_code": "HN1059"},{"object_code": "HN1060"},{"object_code": "VO1013"}]}'
for obj in json['objects']:
print(obj.get('object_code'))
for obj in json[0]['objects']:
print(obj.get('object_code'))
Neither work and I get the error:
TypeError: string indices must be integers
UPDATE 1
The suggested solutions don't work for me, maybe that's because I'm using it in the context of a Scrapy class, here's the full code that throws error
TypeError: 'NoneType' object is not iterable
import json
import scrapy
class MySpider(scrapy.Spider):
name = 'mytest'
start_urls = []
def start_requests(self):
s='{"count": 3,"objects": [{"object_code": "HN1059"},{"object_code": "HN1060"},{"object_code": "VO1013"}]}'
obj = json.loads(s)
for o in obj['objects']:
print(o.get('object_code'))