gpt4 book ai didi

python - 如何从 JSON 响应中提取单个值?

转载 作者:IT老高 更新时间:2023-10-28 20:56:58 25 4
gpt4 key购买 nike

我编写了一些代码来从 Web API 获取数据。我能够解析来自 API 的 JSON 数据,但我得到的结果看起来相当复杂。这是一个例子:

>>> my_json
{'name': 'ns1:timeSeriesResponseType', 'declaredType': 'org.cuahsi.waterml.TimeSeriesResponseType', 'scope': 'javax.xml.bind.JAXBElement$GlobalScope', 'value': {'queryInfo': {'creationTime': 1349724919000, 'queryURL': 'http://waterservices.usgs.gov/nwis/iv/', 'criteria': {'locationParam': '[ALL:103232434]', 'variableParam': '[00060, 00065]'}, 'note': [{'value': '[ALL:103232434]', 'title': 'filter:sites'}, {'value': '[mode=LATEST, modifiedSince=null]', 'title': 'filter:timeRange'}, {'value': 'sdas01', 'title': 'server'}]}}, 'nil': False, 'globalScope': True, 'typeSubstituted': False}

通过这些数据,我可以看到我想要的具体数据:1349724919000 值被标记为 'creationTime'

如何编写直接获取该值的代码?

我不需要任何搜索逻辑来找到这个值。当我查看响应时,我可以看到我需要什么;我只需要知道如何以硬编码的方式将其转换为特定代码以提取特定值。我阅读了一些教程,所以我明白我需要使用 [] 来访问嵌套列表和字典的元素;但我无法弄清楚它对于复杂案例的确切工作原理。

更一般地说,我怎样才能弄清楚数据的“路径”是什么,并为它编写代码?

最佳答案

作为引用,让我们看看原始 JSON 的样子,格式很漂亮:

>>> print(json.dumps(my_json, indent=4))
{
"name": "ns1:timeSeriesResponseType",
"declaredType": "org.cuahsi.waterml.TimeSeriesResponseType",
"scope": "javax.xml.bind.JAXBElement$GlobalScope",
"value": {
"queryInfo": {
"creationTime": 1349724919000,
"queryURL": "http://waterservices.usgs.gov/nwis/iv/",
"criteria": {
"locationParam": "[ALL:103232434]",
"variableParam": "[00060, 00065]"
},
"note": [
{
"value": "[ALL:103232434]",
"title": "filter:sites"
},
{
"value": "[mode=LATEST, modifiedSince=null]",
"title": "filter:timeRange"
},
{
"value": "sdas01",
"title": "server"
}
]
}
},
"nil": false,
"globalScope": true,
"typeSubstituted": false
}

这让我们更清楚地看到数据的结构。

在具体情况下,首先我们要查看我们解析的数据中'value'键下对应的值。那是另一个命令;我们可以以同样的方式访问它的 'queryInfo' 键的值,类似地从那里访问 'creationTime'

要获得所需的值,我们只需将这些访问一个接一个地放置:

my_json['value']['queryInfo']['creationTime'] # 1349724919000

关于python - 如何从 JSON 响应中提取单个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12788217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com