这是我的 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 不是执行此操作的正确方法。