The records in the JSON file look like this (please note what "nutrients" looks like):
{
"id": 21441,
"description": "KENTUCKY FRIED CHICKEN, Fried Chicken, EXTRA CRISPY,
Wing, meat and skin with breading",
"tags": ["KFC"],
"manufacturer": "Kentucky Fried Chicken",
"group": "Fast Foods",
"portions": [
{
"amount": 1,
"unit": "wing, with skin",
"grams": 68.0
},
...
],
"nutrients": [
{
"value": 20.8,
"units": "g",
"description": "Protein",
"group": "Composition"
},
{'description': 'Total lipid (fat)',
'group': 'Composition',
'units': 'g',
'value': 29.2}
...
]
}
The following is the code from the book exercise*. It includes some wrangling and assembles the nutrients for each food into a single large table:
import pandas as pd
import json
db = pd.read_json("foods-2011-10-03.json")
nutrients = []
for rec in db:
fnuts = pd.DataFrame(rec["nutrients"])
fnuts["id"] = rec["id"]
nutrients.append(fnuts)
However, I get the following error and I can't figure out why:
TypeError Traceback (most recent call last)
<ipython-input-23-ac63a09efd73> in <module>()
1 for rec in db:
----> 2 fnuts = pd.DataFrame(rec["nutrients"])
3 fnuts["id"] = rec["id"]
4 nutrients.append(fnuts)
5
TypeError: string indices must be integers
*This is an example from the book Python for Data Analysis
pd.read_json). Please submit data we can actually see your problem on.