【问题标题】:TypeError while trying to parse value from json尝试从 json 解析值时出现 TypeError
【发布时间】:2021-12-28 04:47:31
【问题描述】:

我有这个 Json(代码中间的 ... 是为了减少这个问题中 Json 的数量,完整的 Json 在这里https://pastebin.com/acKCSq8D):

[
  {
    "columnHeader": {
      "dimensions": [
        "ga:city"
      ],
      "metricHeader": {
        "metricHeaderEntries": [
          {
            "name": "ga:users",
            "type": "INTEGER"
          }
        ]
      }
    },
    "data": {
      "rows": [
        {
          "dimensions": [
            "(not set)"
          ],
          "metrics": [
            {
              "values": [
                "984"
              ]
            }
          ]
        },
        {
          "dimensions": [
            "Sao Paulo"
          ],
          "metrics": [
            {
              "values": [
                "555"
              ]
            }
          ]
        },
        ...
        {
          "dimensions": [
            "Xanxere"
          ],
          "metrics": [
            {
              "values": [
                "1"
              ]
            }
          ]
        }
      ],
      ...
    }
  }
]

我正在尝试使用“维度”和“值”项,但使用以下代码:

import json
import pandas as pd

with open('test.json') as f:
    raw_json = json.load(f)

for i in raw_json:
        print(i['data']['rows']['dimensions'])

我收到此错误:

Traceback (most recent call last):
  File "C:\Users\gusta\Desktop\Projects\papai\test.py", line 10, in <module>
    print(i['data']['rows']['dimensions'])
TypeError: list indices must be integers or slices, not str

如何在不返回此类错误的情况下提取维度等值?

【问题讨论】:

    标签: python json pandas


    【解决方案1】:

    这些行被解释为列表,因此您还需要遍历它们以提取维度。这是一个解决方案。

    for i in raw_json:
        for j in i['data']['rows']:
            print(j['dimensions'])
    

    【讨论】:

    • 正是我想要的!感谢您快速而自信的回答
    【解决方案2】:

    您的顶级是列表而不是字典。 尝试raw_json[0] 访问您的字典并从那里开始。

    同样,“rows”访问一个列表,你需要在其中建立索引而不是键入。

    【讨论】:

    • 使用:for i in raw_json: print(i['data']['rows'][1]) 我得到以下回报:{'dimensions': ['Sao Paulo'], 'metrics': [{'values': ['555']}]} 但是:for i in raw_json: print(i[0]) 返回我:KeyError: 0
    • 抱歉,已将 i 更新为 raw_json。不管你没有对嵌套在你的字典中的列表使用类型适当的访问。
    【解决方案3】:

    如果你看到下面的type(i['data']['rows'])list,那么你得到的是TypeError

    In [260]: for i in raw_json:
         ...:     print(type(i))
         ...:     print(type(i['data']))
         ...:     print(type(i['data']['rows']))
         ...:     for j in i['data']['rows']:
         ...:         # print(j['dimensions'])
         ...:         # print(type(j))
         ...:         pass
         ...:
    <class 'dict'>
    <class 'dict'>
    <class 'list'>
    

    【讨论】:

    • 很好的答案,它和上面的答案一样完美。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多