【问题标题】:Write a loop that parses json dictionaries using python编写一个使用python解析json字典的循环
【发布时间】:2015-10-05 09:14:43
【问题描述】:

我是一名初级程序员,我一直在尝试从 API GET 请求中解析一个 json 输出文件,以获取经度和纬度坐标。

JSON 文件看起来像 this

JSON 输入文件是here

我解析 json 文件的代码目前如下所示:

ourResult = js['transactions'][0]['meta']

for majorkey, subdict in ourResult.iteritems():
     print majorkey
for subkey, value in subdict.iteritems():
     print subkey, value

然而,这只是返回“位置”键中的一组值,我正试图更进一步来提取“经度”和“纬度”值。

知道我应该为此使用什么代码吗?

【问题讨论】:

  • 你应该把你的json文件的相关部分放在post中。
  • 你试过ourResult = js['transactions'][1]['meta'](1而不是0)吗?列表中的第一个值不包含纬度/经度数据。
  • 不提供链接,而是发布必要的 json 代码。
  • 谢谢!我包括了我的整个代码。要运行代码,您必须导入 plaid-python,因为这是 Plaid API 测试代码

标签: python json api parsing dictionary


【解决方案1】:

据我了解,您需要类似以下内容:

js = json.loads(response.content)
ourResult = js['transactions'][0]['meta']

for majorkey, subdict in ourResult.iteritems():
     print majorkey
     if type(subdict) == dict:
         for subkey, value in subdict.iteritems():
             print subkey, value

您可以使用代码打印任意深度的dict

def print_dict_rec( indict ):
    for majorkey, subdict in indict.iteritems():
         if type(subdict) == dict:
            print majorkey
            print_dict_rec(subdict)
         else:
            print majorkey, subdict

print_dict_rec(ourResult)

提取键“lat”和“lon”的所有值的代码:

def get_values_json( js, res ):
    if type(js) == list:
        for e in js:
            get_values_json(e, res)
    elif type(js) == dict:
        for k,v in js.iteritems():
            if type(v) ==  dict or type(v) == list:
                get_values_json(v, res)
            else:
                if k == 'lat' or k == 'lon':
                    res[k].append(v)

res = {'lat':[], 'lon':[]}
get_values_json(js, res)
print res

【讨论】:

猜你喜欢
  • 2019-01-18
  • 1970-01-01
  • 1970-01-01
  • 2019-11-06
  • 2021-12-25
  • 2021-02-11
  • 1970-01-01
  • 2019-02-22
  • 1970-01-01
相关资源
最近更新 更多