简体   繁体   English

Python 脚本,用于从 Json 文件中的值中删除所有数据

[英]Python script to remove all data from values in a the Json file

Been searching the forums for this query, and seems fairly straightforward how would I remove all the data from values in JSON file to NULL or "", using python?一直在论坛中搜索此查询,看起来相当简单,我如何使用 python 将 JSON 文件中的所有数据删除到 NULL 或“”?

Example of JSON Before: JSON 之前的示例:


{
     “StringProperty”: “StringValue”,
    “NumberProperty”: 10,
    “FloatProperty”: 20.13,
    “BooleanProperty”: true,
    “EmptyProperty”: null
}

Example of JSON after python script run. python 脚本运行后的 JSON 示例。


{
     “StringProperty”:
    “NumberProperty”:
    “FloatProperty”: 
    “BooleanProperty”: 
    “EmptyProperty”:
}

What I have tried so far:到目前为止我尝试了什么:

def del_none(N):
    """
    Delete keys with the value ``None`` in a dictionary, recursively.

    """
    # For Python 3, write `list(d.items())`; `N.items()` won’t work
    for key, value in list(N.items()):
        if value is None:
            del N[key]
        elif isinstance(value, dict):
            del_none(value)
    return N  # For convenience

But this isn't quite what I want, though.但这并不是我想要的。

Any assistance with writing this python script is welcome;欢迎任何帮助编写此 python 脚本; no idea where to start.不知道从哪里开始。

Thank you.谢谢你。

To remove the json values you could update the recursive function you already have there.要删除 json 值,您可以更新已有的递归 function。

Maybe there is some existing optimized function though...也许有一些现有的优化 function ......

import json

s = '{"StringProperty": "StringValue", ' \
    '"NumberProperty": 10, ' \
    '"FloatProperty": 20.13, ' \
    '"BooleanProperty": true, ' \
    '"EmptyProperty": null,' \
    '"NestedProperty": {' \
        '"NestedStringProperty": "StringValue", ' \
        '"NestedNumberProperty": 10}' \
    '}'
# first convert it to dict
dct = json.loads(s)

def clear_dict_values(d: dict) -> dict:
    for key, value in d.items():
        if isinstance(value, dict):
            d[key] = clear_dict_values(value)
        else:
            d[key] = None  # or ""
    return d

print(clear_dict_values(dct))

Produces:生产:

{'StringProperty': None, 'NumberProperty': None, 'FloatProperty': None, 'BooleanProperty': None, 'EmptyProperty': None, 'NestedProperty': {'NestedStringProperty': None, 'NestedNumberProperty': None}}

If you are sure it will never be nested, you can go for oneliner dct = {k: None for k in dct.keys()}如果你确定它永远不会被嵌套,你可以 go for oneliner dct = {k: None for k in dct.keys()}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM