【问题标题】:TypeError: string indices must be integers while reading the jsonTypeError:读取json时字符串索引必须是整数
【发布时间】:2021-09-11 08:40:15
【问题描述】:

在阅读 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).

【问题讨论】:

  • 这不是有效的 JSON(单引号而不是双引号),但您的错误消息完全无关紧要。请发布您的整个代码。
  • 您的示例不起作用。 req 不是有效的 JSON 结构。你req 变量应该是'''{"XName": "XYZ", "Details": [{"Name": "abc", "Price": "3.2"}, {"Name": "def", "Price": "4.5"}]}'''
  • 已编辑请求。请立即检查
  • JSON 不允许单引号。 'Name' 必须是 "Name"
  • 您如何获得request?如果您从r = requests.get(url) 获取它,请使用r.text 获取json 字符串。 r.json() 获取dict

标签: python json pandas


【解决方案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

【讨论】:

    猜你喜欢
    • 2015-03-06
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    相关资源
    最近更新 更多