0

I'm having trouble parsing this request. It looks like this:

{"randomnumber": {"id":blah, "name":blah, ... }, "randomnumber22": { ... }}

Using python requests, I retrieve the url that returns that data, and decode it so I can try to loop through the fields. I then endup with something like:

{u'randomnumber': {u'id':u'blah', ... }, u'randomnumber22': { .. }}

And when I try to use a for-loop to stroll through the data, it complains that I need to use numbers for string indices. How can I handle this problem properly?

My simplified code:

import requests
network = requests.get('http://example.com')
networkoffers = network.json()
for offers in networkoffers:
    offer['name']

So I'm trying to access network['randomnumber']['name'], going by my initial example of the request data.

0

1 Answer 1

2

You are iterating through the dict's keys, so you need to account for this in your for loop like this:

for offer in networkoffers:  # will look through keys, which are strings and not dicts
    networkoffers[offer]['name']

networkoffers is a dict, and offers (or offer, note the discrepancy) is a key (a string). offers['name'] means nothing to Python, since offers is a string. But networkoffers[offers] is a dict (a value of networkoffers).

Sign up to request clarification or add additional context in comments.

Comments

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.