在python中从JSON字典搜索并获取值

时间:2018-09-10 13:22:40

标签: python json

我有JSON数据,需要获取输入参数名称或简称的GUID值。

  

输入:Script.py名称或简短名称

     

输出:49d01ed7-4285-4bed-a602-0e3bbdc179a1

我是python和JSON解析的新手。任何帮助或建议都会有所帮助

       {
            "countries": [],
            "companies": [
                {
                    "guid": "49d01ed7-4285-4bed-a602-0e3bbdc179a1",
                    "custom_id": null,
                    "name": "Creavath, Sweaine & Mare LTD",
                    "shortname": "Creavath",
                    "href": "https://api.com/ratings/v1/companies/49d01ed7-4285-4bed-a602-0e3bbdc179a1"
}
                {
                    "guid": "edade1ed-9e08-4bc0-bc24-5d05c7903c53",
                    "custom_id": null,
                    "name": "Kremar Levin Natlis & Franklin LTD",
                    "shortname": "Kremar Levin",
                    "href": "https://api.com/ratings/v1/companies/edade1ed-9e08-4bc0-bc24-5d05c7903c53"
                }
]
}

1 个答案:

答案 0 :(得分:1)

试试这个-

import json
json_data = """{
            "countries": [],
            "companies": [
                {
                    "guid": "49d01ed7-4285-4bed-a602-0e3bbdc179a1",
                    "custom_id": null,
                    "name": "Creavath, Sweaine & Mare LTD",
                    "shortname": "Creavath",
                    "href": "https://api.com/ratings/v1/companies/49d01ed7-4285-4bed-a602-0e3bbdc179a1"
                },
                {
                    "guid": "edade1ed-9e08-4bc0-bc24-5d05c7903c53",
                    "custom_id": null,
                    "name": "Kremar Levin Natlis & Franklin LTD",
                    "shortname": "Kremar Levin",
                    "href": "https://api.com/ratings/v1/companies/edade1ed-9e08-4bc0-bc24-5d05c7903c53"
                }
            ]
       }"""
parsed_json = json.loads(json_data)

如果您在json文件(扩展名为.json)中包含json,请使用它-

with open('jsonfile.json', 'r') as f:
    parsed_json = json.load(f)

此后,使用下面的代码获取名称或简称的向导-

user_input = 'Creavath' # for example, user gives this input

for company in parsed_json['companies']:
    if company['name'] == user_input or company['shortname'] == user_input:
        print(company['guid'])
        break
相关问题