获取JSON数组的大小并读取其元素Python

2024-06-02 05:32:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个json数组,如下所示:

{
        "inventory": [
            {
                "Name": "katt"
            },
            {
                "Name": "dog"
            }
        ]
}

现在我想在一个创建并删除元素的程序中访问这个数组,例如“Name”:“dog”。 我不太熟悉如何在python中使用json,但到目前为止,我已经尝试了如下方法:

import json

jsonfile = open("viktor.json", "r")
jsonObj = json.load(jsonfile)

jsonfile.close()

counter = 0
for item in range(len(jsonObj["inventory"])):
    print(jsonObj["inventory"][counter])
    print(type(jsonObj["inventory"][counter]))
    if jsonObj["inventory"][counter] == argOne:
        print("hej")
counter += 1

因此,首先我从json读取数据并将数据存储在一个变量中。 然后我想遍历整个变量,看看是否能找到任何匹配项,如果是,我想删除它。我想我可以在这里使用pop()方法还是什么? 但我似乎无法使if语句正常工作,因为jsonObj[“inventory”][counter]是一个dict,argOne是一个字符串。

我能做什么来代替这个?或者我错过了什么?


Tags: 方法name程序json元素ifcounter数组
2条回答

做出@arvindpdmn建议的改变(更像是Python)。

for index, item in enumerate(jsonObj["inventory"]):
    print(item)
    print(type(item))  # Here we have item is a dict object
    if item['Name'] == argOne:  # So we can access their elements using item['key'] syntax
        print(index, "Match found")

for循环负责遍历包含dict对象的数组,对于每个dict循环,它将创建一个item变量,我们使用该变量来尝试获得匹配。

编辑 为了删除列表中的元素,我建议您使用:

new_list = []
for item in jsonObj["inventory"]:
    if item['Name'] is not argOne:  # add the item if it does not match
        new_list.append(item)

这样,您将以所需列表(新列表)结束。

# Or shorter.. and more pythonic with comprehensions lists.
new_list = [item for item in jsonObj['inventory'] if item['Name'] is not argOne]

您可以使用filter

In [11]: import json

In [12]: with open("viktor.json", "r") as f:
    ...:     jsonObj = json.load(f)
    ...:     

In [13]: argOne = 'katt' #Let's say

In [14]: jsonObj['inventory'] = list(filter(lambda x: x['Name'] != argOne, jsonObj['inventory']))

In [15]: jsonObj
Out[15]: {'inventory': [{'Name': 'dog'}]}

相关问题 更多 >