在 json 文件中搜索值以获取数字 (python)

Search for value in json file to get number (python)

{
    "meta": {
        "code": 200
    },
    "response": {
        "holidays": [
            {
                "name": "New Year's Day",
                "description": "New Year\u2019s Day is celebrated many countries such as in India on the January 1 in the Gregorian calendar.",
                "country": {
                    "id": "in",
                    "name": "India"
                },
                "date": {
                    "iso": "2021-01-01",
                    "datetime": {
                        "year": 2021,
                        "month": 1,
                        "day": 1
                    }
                },
                "type": [
                    "Optional holiday"
                ],
                "locations": "All",
                "states": "All"
            },
            {
                "name": "Lohri",
                "description": "Lohri is a restricted holiday in India",
                "country": {
                    "id": "in",
                    "name": "India"
                },
                "date": {
                    "iso": "2021-01-13",
                    "datetime": {
                        "year": 2021,
                        "month": 1,
                        "day": 13
                    }
                },
                "type": [
                    "National holiday"
                ],
                "locations": "All",
                "states": "All"
            }
        ]
    }
}

这是我的 json 文件另存为 dates.json。
我想在键名中搜索元旦值,然后获取iso键的值。
我该怎么做?
我是 python 和 json 的初学者。所以请告诉我该怎么做
是否有任何搜索算法或库可以帮助我?

一种方法是使用模块 json 和 jsonpath-rw-ext.

使用json模块读取json文件和jsonpath-rw-ext to parse/filter.

https://github.com/sileht/python-jsonpath-rw-ext

我让它适用于你的例子。看看这个。

#!/usr/bin/env python3
import json
import jsonpath_rw_ext

with open('dates.json') as json_file:
    data = json.load(json_file)
    result = jsonpath_rw_ext.parse("$..holidays[?(@.name=='New Year\'s Day')]").find(data)
    print([x.value for x in result])

要获取 iso 值,请使用以下代码。

  #!/usr/bin/env python3
import json
import jsonpath_rw_ext

with open('dates.json') as json_file:
    data = json.load(json_file)
    result = jsonpath_rw_ext.parse("$..holidays[?(@.name=='New Year\'s Day')].date.iso").find(data)
    print(result[0].value)