1

Goal: Iterate over a sub-json looking in 2 keys for a specific string

In PHP it's easy but for python 3, I cannot seems to find a proper way. I tried other solutions I found on the web but I always end up getting an error.

Example JSON:

{
  "main1": {
    "sub1": {
      "prop1": "name1",
      "prop2": "name2"
    },
    "sub2": {
      "prop1": "name1",
      "prop2": "name2"
    },
  },
  "main2": {
    "sub1": {
      "prop1": "name1",
      "prop2": "name2"
    },
    "sub2": {
      "prop1": "name1",
      "prop2": "name2"
    },
  },
}

Code

self.data = dataIO.load_json('data/data.json')

for item in self.data['main1'].items():
  if item['prop1'] == 'name1' or item['prop2'] == 'name1':
    print 'found one'

Error: TypeError: string indices must be integers

1 Answer 1

2

items() returns tuple of key-value, so you either have to use item[1]['prop1']:

for item in x['main1'].items():
  if item[1]['prop1'] == 'name1' or item[1]['prop2'] == 'name1':
    print 'found one'

Or better, make it this way:

self.data = dataIO.load_json('data/data.json')

for key,item in self.data['main1'].items():
  if item['prop1'] == 'name1' or item['prop2'] == 'name1':
    print 'found one'
Sign up to request clarification or add additional context in comments.

1 Comment

I remember I tried something like that, but it must not been the same because this is working. Fantastic, I owe you a cookie! :) (I'll accept this answer in 7 minutes cannot accept earlier) - I took the second example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.