Skip to main content
 首页 » 编程设计

python之使用 Python 比较 JSON 中的值

2025年05月04日14zhoujg

我收到一个相当不舒服的 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