简体   繁体   English

如何检查json列表中是否有属性? 如果没有,我如何仅在缺少的地方添加它?

[英]How can I check if there is a attribute in a json list? And if there is not how do I add it only where is lacking?

I need to check if a .json file has a "quantity": float attribute in all of the lists and add that attribute to the places that doesn't have it alone but I don't know how to do it so (I have no experience with JSON format).我需要检查.json文件是否在所有列表中都有一个"quantity": float属性,并将该属性添加到没有它的地方,但我不知道该怎么做(我有没有使用 JSON 格式的经验)。

I have tried the .append and the .insert functions but none work like I need it to it.我已经尝试了.append.insert函数,但没有一个像我需要的那样工作。

I have a list like this:我有一个这样的列表:

{
    "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"
  },

As you can see the second part doesn't have the "quantity" attribute and I need to add it like "quantity": 0 but have no idea how to do so.正如您所看到的,第二部分没有“数量”属性,我需要像"quantity": 0一样添加它"quantity": 0但不知道该怎么做。 That occurs mutiple times in my list and I would like to know how I could write a code that would find those errors and add the attribute between "name" and "price" like the rest of the list.这在我的列表中多次发生,我想知道如何编写代码来查找这些错误并像列表的其余部分一样在“名称”和“价格”之间添加属性。


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

You can simply assign the attribute and safe it to a file or where ever you need it afterwards.您可以简单地分配属性并将其安全地保存到文件或以后需要的地方。

The easiest way is probably to load the json file into a Python data structure with json.load() , then insert the quantity item where it's missing, then write it to a new json file.最简单的方法可能是使用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)

I ran into the same conundrum the other day and solved it with the below code.前几天我遇到了同样的难题,并用下面的代码解决了它。 I fully accept this is probably the "lazy" way to do it but it is super easy to read.我完全接受这可能是一种“懒惰”的方式,但它非常容易阅读。

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

The approach I have gone for here is Try and Except, lets try and select the quantity key in your data and hey, if its not there lets just add it.我在这里采用的方法是尝试和除外,让我们尝试选择数据中的数量键,嘿,如果没有,让我们添加它。

Let me know how you go with this approach.让我知道你如何使用这种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何摆脱 Anaconda Spyder 编辑器中缺少的类型? - How do I get rid of type lacking in the Anaconda Spyder editor? Python sqlite3-如何制定条件,检查表中的属性是否为列表中的元素之一 - Python sqlite3 - How do I formulate a condition where we check if an attribute in the table is one of the elements in my list 如何将字符串列表转换为dict,其中只有未知索引处的某种类型才能成为键? - How do I convert a list of strings into dict where only a certain type at an unknown index can become the keys? 如何检查对象是否具有属性? - How do I check if an object has an attribute? 如何将我的 json 响应转换为嵌套的 json,其中属性位于另一个“属性”下? - How can I convert my json response to nested json where attributes are under another 'attribute'? 使用Python,如何仅将不同的消息添加到列表? - Using Python, how do I add only distinct messages to a list? 如何通过Elementtree检查属性存在? - How can I check attribute existings by Elementtree? 如何检查列表列表是否为空? - How can I do to check if a list of lists is empty? 如何向 AsyncMock 添加属性? - How do I add an attribute to AsyncMock? 如何在for循环中仅一次添加到列表? - How can I add to list only once in a for loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM