python - 使用 Python 比较 JSON 中的值

标签 python json api parsing python-requests

我收到一个相当不舒服的 JSON,如下所示:

[
{
    "attributes": [
        {
            "type": "COMMAND",
            "name": "COMMAND",
            "value": [
                "buttonState"
            ]
        },
        {
            "type": "std_msgs.msg.Bool",
            "name": "buttonState",
            "value": {
                "data": false
            }
        }
    ],
    "type": "sensor",
    "id": "s_2"
}]

我想比较一段数据(更准确地说 - 按钮状态的值)但我似乎失败了。试过以下:

import requests
import json
yo = 1
switchPost = "http://192.168.0.104:7896/iot/d?k=123456789&i=san_1_switch&d=sw|{}"
robGet = "http://192.168.0.109:10100/robot/sen_2"

r = requests.get(robGet, headers={"content-type":"application/json"})
resp = json.loads(r.text)

for attrs in (resp['attributes']['value']):
    if attrs['data'] == false:
        yo = 100
        break
    
g = requests.post(switchPost.format(yo), headers={"content-type":"text/plain"})
print(r.text)

不幸的是,我收到的错误如下:

for attrs in (resp['attributes']['value']):

TypeError: list indices must be integers, not str

最佳答案

在您的 JSON 中,它被包裹在 [ 然后 ] 中意味着它是一个 JSON 数组,但只有一个元素.

因此,正如您的错误消息所暗示的那样,resp 需要一个整数作为其索引,用于您想要的数组元素。 resp[0] 然后引用

{
    "attributes": [
        {
            "type": "COMMAND",
            "name": "COMMAND",
            "value": [
                "buttonState"
            ]
        },
        {
            "type": "std_msgs.msg.Bool",
            "name": "buttonState",
            "value": {
                "data": false
            }
        }
    ],
    "type": "sensor",
    "id": "s_2"
}

(注意现在没有 [],所以它是一个 JSON 对象)

然后您希望 resp[0]['attributes'] 引用此对象的单个部分,'attributes' 再次引用数组。

因此 for attribute in resp[0]['attributes'] 将允许您遍历此数组。

要获得所需的 bool 值,您需要找到该数组的哪个元素具有 'buttonState''name' 并检查相应的 '值'

总而言之,您可能正在寻找类似的东西:

for attribute in resp[0]['attributes']:
    if attribute['name'] == 'buttonState' and attribute['value']['data'] is False:
        # Do your thing here

关于python - 使用 Python 比较 JSON 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51248455/

相关文章:

python - 如何在 Python 中对 URL 参数进行百分比编码?

c# - System.Text.Json 从 API 调用反序列化嵌套对象 - 数据包装在父 JSON 属性中

php - 为什么 Heroku 服务器上的 Laravel JWT auth 出现此错误

api - Asana:在创建项目时将任务添加到项目

python - 错误 : 'utf8' codec can't decode byte 0x80 in position 0: invalid start byte

python - 多线程 TCP 套接字

python - 不需要的空白导致列扭曲

java - JacksonMapper 反序列化空值

ios - 我应该如何从 json 字符串中读取数据?苹果手机

ios - 应用被拒——如何证明没有使用私有(private)API