在python中递归地删除json对象列表中的null/空值
我有一个具有这样的值的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": []
}
]
BU我想要的最终格式是删除了nulls和空列表项的内容:类似的内容:
[
{
"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": []
}
]
我希望输出排除nulls,空字符串并制造。看起来更干净。 我需要对所有JSON中的所有列表进行递归进行此操作。
甚至不仅仅是递归,如果我可以一口气做而不是遍历每个元素,那将是有帮助的。
我只需要清理列表。
有人可以帮我吗?提前致谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
PS:您的 json 字符串无效。
P.S.: Your json string is not valid.
您可以使用内置
object_pairs_hook
从字符串解码时解析数据。https://docs.python.org/3/library/json。 html#json.load
此函数运行的时间都可以调用
dict()
并删除所有none
none
从列表中使用简单列表, ,否则将数据独自一人,让解码器做这件事。结果:
在您的示例中,您从
stewards
中删除“”
值,如果您需要该行为,则可以用不是无 >不在(无,“”) ..中,但这似乎是一个错误,因为您将空字符串留在其他地方。
You can use the inbuilt
object_pairs_hook
to parse the data as you decode it from your string.https://docs.python.org/3/library/json.html#json.load
This function runs ever time the decoder might call
dict()
and removes allNone
objects from lists as it goes using a simple list comprehension, otherwise leaving the data alone and letting the decoder do it's thing.Result:
in your example you remove the
""
value fromstewards
, if you want that behaviour, you can replaceis not None
withnot in (None, "")
.. but it seemed like that might've been a mistake since you left empty strings in other places.您可以将您的
JSON
转换为dict
然后使用函数
下面的功能,然后将其转换为JSON
再次:感谢NO
You can convert your
json
todict
then use thefunction
below and convert it tojson
again:Thanks to N.O