【问题标题】:Search for value in json file to get number (python)在 json 文件中搜索值以获取数字(python)
【发布时间】:2021-07-01 14:13:52
【问题描述】:
{
    "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"
            }
        ]
    }
}

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

【问题讨论】:

  • 查看 json 模块,该模块会将这个 JSON 作为字典 Pyhthon 对象导入,您可以对其进行迭代。

标签: python json search


【解决方案1】:

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

使用json模块读取json文件,使用jsonpath-rw-ext进行解析/过滤。

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)

【讨论】:

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