Note that there are some explanatory texts on larger screens.

plurals
  1. POPython: TypeError in referencing item in JSON feed
    text
    copied!<p>First, here is a sample JSON feed that I want to read in Python 2.7 with either simplejson or the built in JSON decoder. I am loading the .json file in Python and then searching for a key like "Apple" or "Orange" and when that key is found, I want to bring in the information for it like the types and quantities.</p> <p>Right now there is only 3 items, but I want to be able to search one that may have up to 1000 items. Here is the code: <code><pre> { "fruits": [ { "Apple": [ { "type": "Gala", "quant": 5 }, { "type": "Honeycrisp", "quant": 10 }, { "type": "Red Delicious", "quant": 4 } ] }, { "Banana": [ { "type": "Plantain", "quant": 5 } ] }, { "Orange": [ { "type": "Blood", "quant": 3 }, { "type": "Navel", "quant": 20 } ] } ] }</p> <p></pre></code></p> <p>My sample Python code is as follows:</p> <pre><code> import simplejson as json # Open file fjson = open('/home/teg/projects/test/fruits.json', 'rb') f = json.loads(fjson.read()) fjson.close() # Search for fruit if 'Orange' in json.dumps(f): fruit = f['fruits']['Orange'] print(fruit) else: print('Orange does not exist') </pre> <p></code></p> <p>But whenever I test it out, it gives me this error: <code><pre>TypeError: list indices must be integers, not str</pre></code></p> <p>Was it wrong to have me do a json.dumps and instead should I have just checked the JSON feed as-is from the standard json.loads? I am getting this TypeError because I am not specifying the list index, but what if I don't know the index of that fruit?</p> <p>Do I have to first search for a fruit and if it is there, get the index and then reference the index before the fruit like this? <code><pre>fruit = f['fruits'][2]['Orange']</pre></code></p> <p>If so, how would I get the index of that fruit if it is found so I could then pull in the information? If you think the JSON is in the wrong format as well and is causing this issue, then I am up for that suggestion as well. I'm stuck on this and any help you guys have would be great. :-)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload