簡體   English   中英

從 JSON 文件中刪除項目 - Python

[英]Delete Items from JSON-File - Python

我有一個 JSON 文件,想刪除開頭和結尾部分

{
 "records":
    [{
         "id":"53c5d162-3dd4-41ea-afd1-378b5be1bf04",
         "userid":"u111124027",
         "username":"Testuser",
         "deviceid":"1185494411",
         "devicename":"",
         "start_date":"2020-05-19T06:46:55Z",
         "fee":0.0,
         "currency":"None",
         "billing_state":"Bill",
         "contact_id":"c410618636"
       }], 
"records_remaining":0
}

要移除的部件

{
"records": , 
"records_remaining":0
}

刪除零件的代碼

for element in data:
    if 'records' in element:
        del element['records']

錯誤:

del element['records']
TypeError: 'str' object does not support item deletion

如果我手動移除這些部件,我可以通過以下方式操作 JSON

if 'userid' in element:
    del element['userid']

有沒有可能去掉這兩個部分? 我解決了 rest API 並將 -get 保存到 JSON 文件中。 要繼續使用 JSON 文件,我必須刪除這兩個部分

最后,json 文件應如下所示:

[{
    "id":"53c5d162-3dd4-41ea-afd1-378b5be1bf04",
    "userid":"u111124027",
    "username":"Testuser",
    "deviceid":"1185494411",
    "devicename":"",
    "start_date":"2020-05-19T06:46:55Z",
    "fee":0.0,
    "currency":"None",
    "billing_state":"Bill",
    "contact_id":"c410618636"
}]

在 Python 中加載 JSON object 非常容易。 Python 有一個內置的 package 稱為 json,可用於與 Z0ECD11Z4D7A2DA2874018 數據一起使用。 這是通過使用 json 模塊完成的,它為我們提供了很多方法,其中的 load() 和 load() 方法將幫助我們讀取 JSON 文件。

JSON的反序列化

JSON 的反序列化是指將 JSON 對象轉換為各自的 Python 對象。 load()/loads() 方法用於它。 如果你使用過 JSON 數據來自另一個程序或獲得為 JSON 的字符串格式,那么它可以很容易地使用 load()/loads() 進行反序列化,通常用於從字符串加載,否則根 ZA8CFDE6FDE6331BD4B62AC9字典。

json.load() : json.load() accepts file object, parses the JSON data, populates a Python dictionary with the data and returns it back to you.

句法:

json.loads(file object)

json 的正常讀數將是 -

# Python program to read 
# json file 


import json 

# Opening JSON file 
f = open('data.json',) 

# returns JSON object as  
# a dictionary 
data = json.load(f) 

# saving the records array
records = data["records"]

# Iterating through the json 
# list from records array
for i in data['records']: 
    print(i) 

# Closing file 
f.close() 

現在根據您的用例,您只需要 json 的記錄而不需要其他密鑰。 而不是從 json 中刪除它,您可以使用可以解決問題的data["records"]訪問它。

但是,如果您仍想刪除它,則可以使用 json 中的data["records"]並將其存儲在變量中。 然后,您必須將其寫入文件以保持持久性。

非常感謝,我學到了一些新東西。

現在我可以繼續使用該文件並將其轉換為 CSV。

with open('data.json', 'w') as f:
    json.dump(records, f)

df = pd.read_json('data.json')
df.to_csv('data.csv')


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM