1

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

4

2 回答 2

2

解析后,json对象是 python dict,因此只需在您需要的级别上循环键/值对并打印信息:

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 dicts:print(dic.__class__)returns <class 'dict'>

更新

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

df = pd.Dataframe(columns=['code', 'country_name', 'food'])
[...]
df = df.append([k, item['country_name'], item['reduced_rates']['food']], ignore_index=True)
于 2019-01-22T10:28:54.323 回答
2

您应该使用dict.keys()来获取字典的所有键的列表,然后您可以对其进行迭代并使用它做任何您需要的事情。例如:

for k in text.keys():
   #do something with text[k] or k itself

考虑也用于dict.items()获取键值对:

for k, v in text.items():
    #do something with k and v, where text[k] is v

这对 python 3 有好处,在 python 2 中你应该使用dict.iteritems()

于 2019-01-22T10:29:58.137 回答