我有一個 json 物件(json 字串),它的值如下:
[
{
"id": 1,
"object_k_id": "",
"object_type": "report",
"object_meta": {
"source_id": 0,
"report": "Customers"
},
"description": "Daily metrics for all customers",
"business_name": "",
"business_logic": "",
"owners": [
"[email protected]",
null
],
"stewards": [
"[email protected]",
''
],
"verified_use_cases": [
null,
null,
"c4a48296-fd92-3606-bf84-99aacdf22a20",
null
],
"classifications": [
null
],
"domains": []
}
]
但是我想要的最終格式是洗掉了空值和空串列項的東西:像這樣:
[
{
"id": 1,
"object_k_id": "",
"object_type": "report",
"object_meta": {
"source_id": 0,
"report": "Customers"
},
"description": "Daily metrics for all customers",
"business_name": "",
"business_logic": "",
"owners": [
"[email protected]"
],
"stewards": [
"[email protected]"
],
"verified_use_cases": [
"c4a48296-fd92-3606-bf84-99aacdf22a20"
],
"classifications": [],
"domains": []
}
]
我希望輸出排除空值、空字串并使其看起來更干凈。我需要對我擁有的所有 json 中的所有串列遞回地執行此操作。
甚至比遞回更重要的是,如果我可以一次性完成而不是回圈遍歷每個元素,那將會很有幫助。
我只需要清理串列。
誰能幫我解決這個問題?提前致謝
uj5u.com熱心網友回復:
import json
def recursive_dict_clean(d):
for k, v in d.items():
if isinstance(v, list):
v[:] = [i for i in v if i]
if isinstance(v, dict):
recursive_dict_lookup(v)
data = json.loads("""[{
"id": 1,
"object_k_id": "",
"object_type": "report",
"object_meta": {
"source_id": 0,
"report": "Customers"
},
"description": "Daily metrics for all customers",
"business_name": "",
"business_logic": "",
"owners": [
"[email protected]",
null
],
"stewards": [
"[email protected]"
],
"verified_use_cases": [
null,
null,
"c4a48296-fd92-3606-bf84-99aacdf22a20",
null
],
"classifications": [
null
],
"domains": []
}]""")
for d in data:
recursive_dict_clean(d)
print(data):
[{'id': 1,
'object_k_id': '',
'object_type': 'report',
'object_meta': {'source_id': 0, 'report': 'Customers'},
'description': 'Daily metrics for all customers',
'business_name': '',
'business_logic': '',
'owners': ['[email protected]'],
'stewards': ['[email protected]'],
'verified_use_cases': ['c4a48296-fd92-3606-bf84-99aacdf22a20'],
'classifications': [],
'domains': []}]
PS:您的 json 字串無效。
uj5u.com熱心網友回復:
您可以將其轉換json為dict然后使用function以下內容并json再次將其轉換為:
def clean_dict(input_dict):
output = {}
for key, value in input_dict.items():
if isinstance(value, dict):
output[key] = clean_dict(value)
elif isinstance(value, list):
output[key] = []
for item in value:
if isinstance(value, dict):
output[key].append(clean_dict(item))
elif value not in [None, '']:
output[key].append(item)
else:
output[key] = value
return output
感謝NO
uj5u.com熱心網友回復:
您可以在從字串中解碼資料時使用內置函式object_pairs_hook來決議資料。
https://docs.python.org/3/library/json.html#json.load
每當解碼器可能呼叫并使用簡單的串列推導從串列中dict()洗掉所有物件時,此函式都會運行,否則將不理會資料并讓解碼器完成它的事情。None
#!/usr/bin/env python3
import json
data_string = """[
{
"id": 1,
"object_k_id": "",
"object_type": "report",
"object_meta": {
"source_id": 0,
"report": "Customers"
},
"description": "Daily metrics for all customers",
"business_name": "",
"business_logic": "",
"owners": [
"[email protected]",
null
],
"stewards": [
"[email protected]",
""
],
"verified_use_cases": [
null,
null,
"c4a48296-fd92-3606-bf84-99aacdf22a20",
null
],
"classifications": [
null
],
"domains": []
}
]"""
def json_hook(obj):
return_obj = {}
for k, v in obj:
if isinstance(v, list):
v = [x for x in v if x is not None]
return_obj[k] = v
return return_obj
data = json.loads(data_string, object_pairs_hook=json_hook)
print(json.dumps(data, indent=4))
結果:
[
{
"id": 1,
"object_k_id": "",
"object_type": "report",
"object_meta": {
"source_id": 0,
"report": "Customers"
},
"description": "Daily metrics for all customers",
"business_name": "",
"business_logic": "",
"owners": [
"[email protected]"
],
"stewards": [
"[email protected]",
""
],
"verified_use_cases": [
"c4a48296-fd92-3606-bf84-99aacdf22a20"
],
"classifications": [],
"domains": []
}
]
in your example you remove the "" value from stewards, if you want that behaviour, you can replace is not None with not in (None, "").. but it seemed like that might've been a mistake since you left empty strings in other places.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/455735.html
