首页 > 解决方案 > 在json中条带化尾迹空格

问题描述

我有一个包含 1000 多个条目的大 json 文件。这个 json 被送入下游库进行进一步处理。我正在尝试寻找一种更简单的方法来消除值部分中的所有尾随空格。

{
    "Country": [
        {
            "country_name": "Germany ",
            "country_capital": " Berlin",
            "concept_description": "Germany is also known as Deutschland ",
            "country_cities": [
                "Frankfurt"
            ],
            "neighbouring_countries": [
                " Belgium",
                "France "
            ],
            "country_group": "Europe "
        },
            {
            "country_name": " France ",
            "country_capital": " Paris",
            "concept_description": "Effiel Tower is in paris ",
            "country_cities": [
                " montpellier"
            ],
            "neighbouring_countries": [
                " Belgium",
                "Spain "
            ],
            "country_group": "Europe "
        }
    ]
}

我试图使用String.strip()和列出理解来实现这一点mylist = [[x.strip() for x in y] for y in mylist]。但是,某些键的值是列表,有些只是字符串。

标签: pythonjsonstrip

解决方案


您可以使用递归函数来剥离所有内容吗?

def strip(value):
    if isinstance(value, str):
        return value.strip()
    if isinstance(value, list):
        return list(map(strip, value))
    # handle dict etc, by recursive call to `strip()`

如果结构是一致的,例如。neighbouring_countries始终是一个列表,您可以使用任何数据验证库。我更喜欢schema我自己


推荐阅读