简体   繁体   English

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

[英]Search and get value from JSON dictionary in python

I have JSON data, need to get GUID value of name or shortname of input argument. 我有JSON数据,需要获取输入参数名称或简称的GUID值。

Input : Script.py NAME or SHORT NAME 输入:Script.py NAME或SHORT NAME

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

Im new to python and JSON parsing. 我是python和JSON解析的新手。 Any help or suggestion will be helpfull 任何帮助或建议都会有所帮助

       {
            "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"
                }
]
}

Try this- 尝试这个-

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)

If you have json in a json file (with extension as .json), use this-- 如果您在json文件(扩展名为.json)中包含json,请使用此命令-

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

After this, use the code below to get the guid for name or short name- 之后,请使用以下代码获取名称或简称的GUID-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM