-1

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'))
Adam
  • 6,041
  • 36
  • 120
  • 208
  • your `json` contains JSON content : so a string, not a python structure – azro Dec 21 '22 at 20:25
  • Your JSON is a string (thank you for correctly using the word JSON!). But why do you think you can manipulate that serialized data like unserialized data? – juanpa.arrivillaga Dec 21 '22 at 20:29
  • You could post a new question about your update. Include Scrapy in the tags if it's required to reproduce the issue. See [mre]. – wjandrea Dec 21 '22 at 21:38
  • @wjandrea I'll do that. As a best practice, should I delete this question since it's a duplicate anyway? Or would that not be fair to folks who already provided answers? – Adam Dec 22 '22 at 07:20
  • @Adam I don't see any reason to keep it around personally, but I don't know if you can delete it when there's an answer with a positive score. – wjandrea Dec 22 '22 at 19:33
  • 1
    @wjandrea just tried to delete, I indeed can't "You cannot delete this question as others have invested time and effort into answering it." – Adam Dec 23 '22 at 09:56

2 Answers2

2

You need to load fom the JSON content to python structure

import json

value = '{"count": 3,"objects": [{"object_code": "HN1059"},{"object_code": "HN1060"},{"object_code": "VO1013"}]}'
content = json.loads(value)

for obj in content['objects']:
    print(obj.get('object_code'))
azro
  • 53,056
  • 7
  • 34
  • 70
0

Use json.loads to convert the JSON string to a dict.

import json
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'))
Unmitigated
  • 76,500
  • 11
  • 62
  • 80