代码之家  ›  专栏  ›  技术社区  ›  marjun

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

  •  0
  • marjun  · 技术社区  · 7 年前

    我有JSON数据,需要获取输入参数的name或shortname的GUID值。

    输出: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 回复  |  直到 7 年前
        1
  •  1
  •   njras    7 年前

    试试这个-

    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)
    

    之后,使用下面的代码获取name或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