我有:
def decoder(o):
return o.get("fruits")
array = '{"fruits": [{"apple": "red"}, {"banana": "yellow"}, "orange"]}'
data = json.loads(array, object_hook=decoder)
print(data)
返回[None, None, 'orange']
。
但是,如果我不使用object_hook
执行下面的操作n = json.loads(array)
print(n.get("fruits"))
返回[{'apple': 'red'}, {'banana': 'yellow'}, 'orange']
。
我如何使用object_hook返回[{'apple': 'red'}, {'banana': 'yellow'}, 'orange']
而不是[None, None, 'orange']
?我的代码的哪个部分导致它返回None?
将使用object_hook
的返回值代替dict
Notice: return value of object_hook would replace all dict object in your json string
# the reason you get None:
# 1 inner dict {"apple": "red"} apply "object_hook"
# 2 return o.get("fruits") --> None
您可以尝试使用以下代码作为参考:
import json
def decoder(o):
if o.get("fruits"):
return o["fruits"]
return o
array = '{"fruits": [{"apple": "red"}, {"banana": "yellow"}, "orange"]}'
data = json.loads(array, object_hook=decoder)
print(data)
了解发生的事情的一个好方法是打印o
:
{'apple': 'red'}
{'banana': 'yellow'}
{'fruits': [None, None, 'orange']}
[None, None, 'orange']
现在这个谜团似乎被解开了。至于如何解决它,我认为不应该这样使用。当然,您可以保留当前的代码,然后过滤列表中所有非None
的元素,如:
result_list = [x if x is not None for x in result_list]
其中result_list
存储来自json.loads