【问题标题】:Read value from an array of multiple objects (JSON)从多个对象的数组中读取值 (JSON)
【发布时间】:2019-01-21 23:32:38
【问题描述】:

我是编码新手,并尝试使用 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>

【问题讨论】:

  • 请更具体地说明“我正在寻找一个函数(inputID):”的意思?您是否了解其中的某些部分?

标签: python arrays json object


【解决方案1】:

我相信您正在寻找这个:

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

这将遍历json_data 中的每个索引,并检查该索引的 ID 是否与您要求的相同,如果找到匹配的内容,它将返回该内容并且函数完成。

如果你想用这个做其他事情,你可以通过在代码返回之前编辑代码来做到这一点。

【讨论】:

  • 我在没有条件的情况下在第一步中尝试了您的代码(以使其更简单并防止错误):for x in json_data: return x I get an error: TypeError: 'Response' object is not iterable
  • 你一定是做错了什么,因为你将 json_data 定义为一个列表(json_data=[]),它必须是可迭代的。
  • 当我返回时(json_data)它返回: [ { "ID": 123, "CODE": 4117, "STATUS": "on" } ] 我是否理解这是一个数组对象?那么 [] 是数组,而 {} 是第一个对象吗? return(json_data[0]) 给出错误 TypeError: 'Response' object does not support indexing
  • 是的,[] 是一个字典数组(它们是由{} 封装的东西),因此我对为什么会收到数组的迭代错误感到困惑,因为那些是可迭代的。
【解决方案2】:

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

return jsonify(json_data)

但这似乎使我的数组不可用/不可迭代。我试过了

return(json_data)

输出看起来一样,但知道我可以使用

for x in json_data:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    • 2013-03-06
    相关资源
    最近更新 更多