前几天群里发了个面试题,做了一下。英语不好,代码写完了,才发现理解错了。在此特别的记录下这个小题。
大概意思就是,传入json,将value为null,[],{},""," "的这一条数据去掉,可以传入任意的json数据。
接下来看看我写的代码
import json
import time
z = """{
"first_ name": "Jane",
"last_ name": "Smith",
"email": "jane .smith@wyng.com",
"gender": null,
"invitations": [
{
"from": "",
"code": null
}
],
"company": {
"name": "",
"industries": {"dd":""},
"industries1": {"dd":"1"}
},
"address": {
"city": "New York",
"state": "NY",
"zip": "10011",
"street": " "
}
}"""
def isTrue(d):
z = [False," "]
if d not in z:
return d
def jsonToEmpty(l):
if type(l) == list:
ll = []
for i in l:
z = jsonToEmpty(i)
o = isTrue(z)
if o:
ll.append(z)
if ll:
return ll
elif type(l) == dict:
dd = {}
for k,v in l.items():
o = isTrue(v)
if o:
z = jsonToEmpty(o)
o = isTrue(z)
if o:
dd[k] = z
return dd
else:
o = isTrue(l)
if o:
return o
if __name__ == '__main__':
PP = json.loads(z)
p = jsonToEmpty(PP)
print(p)
代码水平有限,看群里别人写的也不错,记录了一下
info_dict = {
"first_ name": "Jane",
"last_ name": "Smith",
"email": "jane .smith@wyng.com",
"gender": "null",
"gender1": " ",
"gender2": "",
"invitations": [
{
"from": "",
"code": "null"
}
],
"company": {
"name": "",
"industries": []
},
"address": {
"city": "New York",
"state": "NY",
"zip": "10011",
"street": " "
}
}
def extraDictList(info):
if type(info) == dict:
re_info: dict = {}
for key, value in info.items():
if type(value) == dict or type(value) == list:
re = extraDictList(value)
if len(re) != 0:
re_info[key] = re
elif type(value) == str and value not in ["", " ", "null"]:
re_info[key] = value
return re_info
elif type(info) == list:
re_info: list = []
for value in info:
if type(value) == dict or type(value) == list:
re = extraDictList(value)
if len(re) != 0:
re_info.append(re)
else:
print("error list")
return re_info
else:
print("error")
if __name__ == '__main__':
re = extraDictList(info_dict)
print(re)