gpt4 book ai didi

python - 尝试从 json 解析值时出现类型错误

转载 作者:行者123 更新时间:2023-12-02 18:26:50 24 4
gpt4 key购买 nike

我有这个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

如何提取尺寸等值而不返回此类错误?

最佳答案

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

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

关于python - 尝试从 json 解析值时出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70000479/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com