如何检查json列表中是否有属性?如果没有,我怎样才能把它加在缺少的地方呢?

2024-09-30 01:32:21 发布

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

我需要检查一个.json文件是否在所有列表中都有"quantity": float属性,并将该属性添加到没有单独属性的地方,但我不知道如何这样做(我没有使用JSON格式的经验)

我试过.append.insert函数,但没有一个像我需要的那样工作

我有这样一个清单:

{
    "id": 9746439,
    "name": "Home Theater LG com blu-ray 3D, 5.1 canais e 1000W",
    "quantity": 80,
    "price": 2199.0,
    "category": "Eletrônicos"
  },
  {
    "id": 2162952,
    "name": "Kit Gamer acer - Notebook + Headset + Mouse",
    "price": 25599.0,
    "category": "Eletrônicos"
  },

如您所见,第二部分没有“quantity”属性,我需要像"quantity": 0那样添加它,但不知道如何添加。这种情况在我的列表中出现过多次,我想知道如何编写一个代码来查找这些错误,并像列表的其他部分一样在“name”和“price”之间添加属性


Tags: 文件nameidjson列表属性格式地方
3条回答

jString = '''{
    "lst":[
    {
        "id": 9746439,
        "name": "Home Theater LG com blu-ray 3D, 5.1 canais e 1000W",
        "quantity": 80,
        "price": 2199.0,
        "category": "Eletrônicos"
     },
      {
        "id": 2162952,
        "name": "Kit Gamer acer - Notebook + Headset + Mouse",
        "price": 25599.0,
        "category": "Eletrônicos"
      }
    ]
    }'''
jObj = json.loads(jString)
for x in jObj["lst"]:
    if "quantity" not in x:
        x["quantity"] = 0

您可以简单地分配属性并将其安全地保存到一个文件或以后需要它的任何地方

最简单的方法可能是将json文件加载到带有json.load()的Python数据结构中,然后在缺少的地方插入quantity项,然后将其写入新的json文件

import json

# open the input file and load the contents into a python datastructure
with open('myfile.json') as input:
    data = json.load(input)

# iterate over each item
for item in data:
    # if "quantity" is not present, add it
    if 'quantity' not in item:
        item['quantity'] = 99.99

# write the updated data to a new file
with open('myfile_new.json', 'w') as output:
    json.dump(data, output)

前几天我遇到了同样的难题,并用下面的代码解决了它。我完全接受这可能是“懒惰”的方式做它,但它是超级容易阅读

import json

json_string = '''{"results":[
{
    "id": 9746439,
    "name": "Home Theater LG com blu-ray 3D, 5.1 canais e 1000W",
    "quantity": 80,
    "price": 2199.0,
    "category": "Eletrônicos"
  },
  {
    "id": 2162952,
    "name": "Kit Gamer acer - Notebook + Headset + Mouse",
    "price": 25599.0,
    "category": "Eletrônicos"
  }]}'''

json_dict = json.loads(json_string)

for item in json_dict["results"]:
    try:
        item['quantity']
    except:
        item['quantity'] = 0

我在这里使用的方法是Try and Except,让我们尝试选择数据中的quantity键,嘿,如果没有,让我们添加它

让我知道你怎么用这个方法

相关问题 更多 >

    热门问题