在這里我的問題我得到了一個包含空 obj 的 json 檔案,我想從這個 json 檔案中洗掉它們并將其保存在一個新的 json 檔案中。
這里我的 json 示例稱為 db_origin.json :
[
# Would like remove this
#====================#
{},
{},
{},
{},
{},
#====================#
{
"model": "auth.user",
"pk": *,
"fields": {
"password": "*********",
"last_login": "********",
"is_superuser": true,
"username": "******",
"first_name": "",
"last_name": "",
"email": "",
"is_staff": true,
"is_active": true,
"date_joined": "2016-12-08T11:04:07",
"groups": [
1
],
"user_permissions": []
}
},
{},
{},
]
我試圖做的事情:
import json
def read_write():
with open('db_origin.json') as json_file:
lines = json_file.readlines()
for line in lines:
line.replace((' {},\n'), "")
with open('cleaned.json', 'w') as f:
json.dump(lines, f, indent=4)
read_write()
uj5u.com熱心網友回復:
首先,這不是有效的 JSON,因此在修復它并使其成為有效的 JSON 之后,您可以通過這種方式從串列中過濾空字典。
import json
json_str='''[{},{},{},{},{},{"model":"auth.user","pk":"*","fields":{"password":"*********","last_login":"********","is_superuser":true,"username":"******","first_name":"","last_name":"","email":"","is_staff":true,"is_active":true,"date_joined":"2016-12-08T11:04:07","groups":[1],"user_permissions":[]}},{},{}]'''
python_list = json.loads(json_str)
filtered_empty = list(filter(None, python_list))
print(filtered_empty)
完整代碼:
import json
def read_write():
with open('db_origin.json') as json_file:
python_list = json.load(json_file)
filtered_empty = list(filter(None, python_list))
with open('cleaned.json', 'w') as f:
json.dump(filtered_empty, f, indent=4)
read_write()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/385795.html
