类型错误:读取 json 时字符串索引必须是整数

时间:2021-06-29 06:22:49

标签: python json pandas

在阅读 json 请求时,我得到了

TypeError: string indices must be integers error.

下面是请求

"{'Name': 'XYZ', 'Details': [{'Name': 'hhh', 'Price': '5.79'}, 
{'Name': ' abc', 'Price': '2.79'},
 {'Name': 'def', 'Price': '2.99'}, 
 {'Name': ' ghi', 'Price': '1.29'}, 
{'Name': 'ijk',  'Price': '1.49'}]}"

我想从上述请求中获取 Details 键的值。

我尝试了以下方法,它们都不起作用

data = json.loads(req)

data = json.dumps(req)

ast.literal_eval(data).

1 个答案:

答案 0 :(得分:1)

如果您的 req 变量定义如下:

req = '{"Name": "XYZ", "Details": [{"Name": "hhh", "Price": "5.79"}, {"Name": "abc", "Price": "2.79"}, {"Name": "def", "Price": "2.99"},  {"Name": "ghi", "Price": "1.29"}, {"Name": "ijk",  "Price": "1.49"}]}'

您可以使用pd.json_normalize

df = pd.json_normalize(json.loads(req), 'Details', ['Name'], meta_prefix='X') \
       .astype({'Price': float})
>>> df
  Name  Price XName
0  hhh   5.79   XYZ
1  abc   2.79   XYZ
2  def   2.99   XYZ
3  ghi   1.29   XYZ
4  ijk   1.49   XYZ

>>> df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   Name    5 non-null      object
 1   Price   5 non-null      float64
 2   XName   5 non-null      object
dtypes: float64(1), object(2)
memory usage: 248.0+ bytes