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

问题描述 投票:-1回答:3

我需要检查.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": 0一样添加它,但不知道怎么做。这在我的列表中出现了很多次,我想知道如何编写一个代码来查找这些错误,并在“名称”和“价格”之间添加属性,就像列表的其余部分一样。

python json
3个回答
0
投票

最简单的方法可能是使用json.load()将json文件加载到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)

0
投票

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

您可以简单地分配属性并将其安全地保存到文件中,或者之后需要它的位置。


0
投票

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

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,让我们尝试选择数据中的数量键,嘿,如果它不在那里就可以添加它。

让我知道你如何采用这种方法。

© www.soinside.com 2019 - 2024. All rights reserved.