【问题标题】:Search and get value from JSON dictionary in python在 python 中从 JSON 字典中搜索并获取值
【发布时间】:2018-09-10 13:22:40
【问题描述】:

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

输入:Script.py NAME 或 SHORT NAME

输出: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"
                }
]
}

【问题讨论】:

  • 你在 python 中使用什么来检索 JSON 输入?由于没有太多上下文,我不知道如何为您提供更多帮助
  • 您发布的不是有效的 JSON。请编辑问题以包含您迄今为止尝试过的代码。

标签: python json


【解决方案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)

在此之后,使用下面的代码获取名称或短名称的 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

【讨论】:

    猜你喜欢
    • 2022-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多