如何搜索json文件以返回满足特定条件的值?

时间:2017-06-06 05:59:29

标签: python json python-3.x anaconda

这是我的json文件:

test -s output.txt

以色列说,如何提取来自特定地点的用户的显示名称?我试图为相同但写入语法错误编写嵌套查询。

4 个答案:

答案 0 :(得分:1)

import json

fp = open('myfile.json', 'r')
data = json.load(fp)

for user in data['items']:
    if user['location'] == 'Israel':
        print (user['display_name'])

答案 1 :(得分:0)

我认为你正在使用这种方法:

   data = {"items":[{"reputation":6623,"user_id":836,"location":"Durham, United Kingdom","link":"https://datascience.stackexchange.com/users/836/neil-slater","display_name":"Neil Slater"},{"reputation":6267,"user_id":381,"location":"Silicon Valley","link":"https://datascience.stackexchange.com/users/381/emre","display_name":"Emre"},{"reputation":5033,"user_id":2452,"location":"Atlanta, GA","link":"https://datascience.stackexchange.com/users/2452/aleksandr-blekh","display_name":"Aleksandr Blekh"},{"reputation":3537,"user_id":11097,"location":"Gurgaon, India","link":"https://datascience.stackexchange.com/users/11097/dawny33","display_name":"Dawny33"},{"reputation":3257,"user_id":21,"location":"London, United Kingdom","link":"https://datascience.stackexchange.com/users/21/sean-owen","display_name":"Sean Owen"}]}


    for key,value in data.items():
             for i in range(len(value)):
                     if 'United Kingdom' in value[i]['location']:
                             print value[i]['display_name']

输出:

Neil Slater
Sean Owen

答案 2 :(得分:0)

示例代码:

import json

location = 'United Kingdom'
jso = '''{"items":[{"reputation":6623,"user_id":836,"location":"Durham, United Kingdom","link":"https://datascience.stackexchange.com/users/836/neil-slater","display_name":"Neil Slater"},{"reputation":6267,"user_id":381,"location":"Silicon Valley","link":"https://datascience.stackexchange.com/users/381/emre","display_name":"Emre"},{"reputation":5033,"user_id":2452,"location":"Atlanta, GA","link":"https://datascience.stackexchange.com/users/2452/aleksandr-blekh","display_name":"Aleksandr Blekh"},{"reputation":3537,"user_id":11097,"location":"Gurgaon, India","link":"https://datascience.stackexchange.com/users/11097/dawny33","display_name":"Dawny33"},{"reputation":3257,"user_id":21,"location":"London, United Kingdom","link":"https://datascience.stackexchange.com/users/21/sean-owen","display_name":"Sean Owen"}]}'''

dic = json.loads(jso)

for entry in dic['items']:
    if location.lower() in entry['location'].lower():
        print (entry['display_name'])

输出:

Neil Slater
Sean Owen

答案 3 :(得分:0)

你可以使用这样的列表理解:

import json
jsd = json.loads(<JSON STRING>) #  This return a dict object
displayNamesList = [dn['display_name'] for dn in jsd.values()[0] if 'Israel' in dn['display_name']]

但是最重要的是你需要检查一个结构良好的json结构。我使用http://codebeautify.org/jsonviewer来验证json结构。

希望这对你有所帮助。