Синтаксис для type()
выглядит следующим образом: if type(v) is list:
(не ==
)
Итак, вы хотите что-то вроде этого:
import json
from collections import OrderedDict
raw_text = '{"DICT":{"List of dict":[{"K1":"V1","K2":"V2","K3":"V3","K4":[{"K4_1_1":"V4_1"},{"K4_2_1":"V4_2"},{"K4_3_1":null}],"K5 is a list of Dict":[{"K5_1_1":"V5_1","K5_1_2":"V5_2","K5_1_3":"V5_3","K5_1_4":"V5_4"},{"K5_2_1":"V5_1","K5_2_2":"V5_2","K5_2_3":"V5_3","K5_2_4":"V5_4"}]},{"K1":"V1","K2":"V2","K3":"V3","K4":[{"K4_1_1":"V4_1_1"},{"K4_2_1":"V4_2_1"}],"K5":{"K5_1_1":"V_1_1","K5_1_2":"V_1_2","K5_1_3":null,"K5_1_4":null}}]}}'
raw_json = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(raw_text)
def remove_nulls(x):
if type(x) is list:
return [remove_nulls(v) for v in x if v is not None]
elif type(x) is OrderedDict:
return OrderedDict((k,remove_nulls(v)) for k,v in x.items() if v is not None)
else:
return x
de_nullified_json = remove_nulls(raw_json)
print(json.dumps(de_nullified_json, indent=2))
Вывод:
{
"DICT": {
"List of dict": [
{
"K1": "V1",
"K2": "V2",
"K3": "V3",
"K4": [
{
"K4_1_1": "V4_1"
},
{
"K4_2_1": "V4_2"
},
{}
],
"K5 is a list of Dict": [
{
"K5_1_1": "V5_1",
"K5_1_2": "V5_2",
"K5_1_3": "V5_3",
"K5_1_4": "V5_4"
},
{
"K5_2_1": "V5_1",
"K5_2_2": "V5_2",
"K5_2_3": "V5_3",
"K5_2_4": "V5_4"
}
]
},
{
"K1": "V1",
"K2": "V2",
"K3": "V3",
"K4": [
{
"K4_1_1": "V4_1_1"
},
{
"K4_2_1": "V4_2_1"
}
],
"K5": {
"K5_1_1": "V_1_1",
"K5_1_2": "V_1_2"
}
}
]
}
}