0

After doing an API request I get the json 'data' this has each record in a different set if curly brackets under the results square brackets.

I want to extract the numbers and store/print them separated with a comma.

so requested output

0010041,0010042

I have tried using the below however it comes back with the following error.

TypeError: list indices must be integers or slices, not str

If the results only has one set of brackets it works fine, do I have to convert the multiple results into one so and then extract all the times when 'number' appears?

import json
import sys

#load the data into an element
data={'result': [{'number': '0010041', 'day_of_week': 'monday'}, {'number': '0010042', 'day_of_week': 'tuesday'}]}

#dumps the json object into an element
json_str = json.dumps(data)

#load the json to a string
resp = json.loads(json_str)

print (resp['result'])
print (resp['result']['number'])
2
  • You need to first state which item in result you want the number reg . esp['result'][0]['number'] Commented Jan 20, 2020 at 12:08
  • add this line print([i['number'] for i in resp['result']]) instead of print (resp['result']['number']) in code. Commented Jan 20, 2020 at 12:10

1 Answer 1

4

Error message is clear: you are trying to access a list of dicts and you aren't doing it correctly.

Replace your last line with:

for i in resp['result']:
    print(i['number'])

Update:

As suggested in comments, you can use list comprehension. So to get your desired result, you can do:

print(",".join([i['number'] for i in resp['result']]))
Sign up to request clarification or add additional context in comments.

1 Comment

You can use a list comprehension, which is a powerful feature of python to extract those numbers from list of dicts. print([i['number'] for i in resp['result']])

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.