gpt4 book ai didi

python - 如何使用 Python 在 key 未知时解析 Json?

转载 作者:行者123 更新时间:2023-12-01 21:59:17 25 4
gpt4 key购买 nike

这是我的 Json 示例:

text = {"rates":{
"AT":{
"country_name":"Austria",
"standard_rate":20,
"reduced_rates":{
"food":10,
"books":10
}
}
}}

现在“AT”是国家代码。它不是固定的。也可以是GB、IT等……

我想解析这个 Json 并从中获取如下列:

rates.AT   rates.AT.country_name   rates.AT.reducted_rates.food
AT Austria 10

也可以重命名为:

code        country_name               food
AT Austria 10

例如,在另一次运行中我有:

text = {"rates":{
"IT":{
"country_name":"Italy",
"standard_rate":20,
"reduced_rates":{
"food":13,
"books":11
}
}
}}

那么它需要是:

rates.IT   rates.IT.country_name   rates.IT.reducted_rates.food
IT Italy 13

也可以重命名为:

 code        country_name               food
IT Italy 13

我该怎么做?

编辑:

如果可能的话,使用@GPhilo 回答我更愿意将数据作为 Pandas 数据框获取。就像是?

df = pd.DataFrame()
for k,item in dic['rates'].items(): # use iteritems() if you're on Python 2
line = '{};{};{}'.format(k, item['country_name'], item['reduced_rates']['food'])
df = df.append(line, ignore_index=True)

这行不通,因为 line 不是执行此操作的正确方法。

最佳答案

一旦解析,json对象是 python dict s,因此只需在您需要的级别遍历键/值对并打印信息:

import json

dic = json.loads('''
{"rates":{
"AT":{
"country_name":"Austria",
"standard_rate":20,
"reduced_rates":{
"food":10,
"books":10
}
}
}}
''')

for k,item in dic['rates'].items(): # use iteritems() if you're on Python 2
print('{};{};{}'.format(k, item['country_name'], item['reduced_rates']['food']))

根据需要格式化输出,你需要的三个值就是format中的三个调用上面的代码。运行示例返回:

AT;Austria;10

编辑:修改答案

一旦解析,json 对象 python 字典:print(dic.__class__)返回 <class 'dict'> .

更新

在回复问题中的编辑时,不是附加格式化字符串,而是附加值:

df = pd.Dataframe(columns=['code', 'country_name', 'food'])
[...]
df = df.append([k, item['country_name'], item['reduced_rates']['food']], ignore_index=True)

关于python - 如何使用 Python 在 key 未知时解析 Json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54306022/

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