[英]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?
我需要檢查.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
一樣添加它"quantity": 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
您可以簡單地分配屬性並將其安全地保存到文件或以后需要的地方。
最簡單的方法可能是使用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)
前幾天我遇到了同樣的難題,並用下面的代碼解決了它。 我完全接受這可能是一種“懶惰”的方式,但它非常容易閱讀。
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
我在這里采用的方法是嘗試和除外,讓我們嘗試選擇數據中的數量鍵,嘿,如果沒有,讓我們添加它。
讓我知道你如何使用這種方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.