从多个对象的数组中读取值(JSON)

时间:2019-01-21 23:32:39

标签: python arrays json object

我是编码的新手,并尝试使用python构建HTTP-API。我有JSON格式的对象数组。我想读取这些对象之一的值。

在我的python脚本中,我将数据库表附加到对象数组。我正在寻找一种在这些对象之一中选择一个值的解决方案。

我有一个功能:

cur.execute(<SELECT STATEMENT>)
row_headers=[x[0] for x in cur.description]
response = cur.fetchall()
json_data=[]
for result in response:
    json_data.append(dict(zip(row_headers,result))) 
return jsonify(json_data)

返回结果如下:

[
    {
        "ID": 123,
        "CODE": 4117,
        "STATUS": "off",
    },
    {
        "ID": 345,
        "CODE": 5776,
        "STATUS": "on",
    }
]

我正在寻找一个函数(inputID):

where ID = inputID
set currentcode = <CODE>
set currentstatus = <STATUS>
<Do something with currentcode and currentstatus>

2 个答案:

答案 0 :(得分:0)

我相信您正在寻找:

def return_with_id(input_id):
    for x in json_data:
        if x['ID'] == input_id:
            return x

这将遍历json_data中的每个索引,并检查该索引的ID是否等于您要求的ID,如果找到匹配的对象,则将其返回并完成该函数。

如果您要执行其他操作,则只需在返回代码之前对其进行编辑即可。

答案 1 :(得分:0)

我认为我发现了错误。我不完全知道会发生什么:

return jsonify(json_data)

但是,这似乎使我的数组无法使用/可迭代。我尝试过

return(json_data)

输出看起来相同,但是知道我可以使用

for x in json_data: