小编典典

如何从JSON文件中的每个值中删除空格和换行符?

json

我有一个JSON具有以下结构的文件:

{
    "name":[
        {
            "someKey": "\n\n   some Value   "
        },
        {
            "someKey": "another value    "
        }
    ],
    "anotherName":[
        {
            "anArray": [
                {
                    "key": "    value\n\n",
                    "anotherKey": "  value"
                },
                {
                    "key": "    value\n",
                    "anotherKey": "value"
                }
            ]
        }
    ]
}

现在,我要为文件中的strip每个值关闭所有空白和换行符JSON。有什么方法可以遍历字典的每个元素以及嵌套的字典和列表吗?


阅读 992

收藏
2020-07-27

共1个答案

小编典典

现在,我要为JSON文件中的每个值剥离所有空白和换行符

使用pkgutil.simplegeneric()创建一个辅助函数get_items()

import json
import sys
from pkgutil import simplegeneric

@simplegeneric
def get_items(obj):
    while False: # no items, a scalar object
        yield None

@get_items.register(dict)
def _(obj):
    return obj.items() # json object. Edit: iteritems() was removed in Python 3

@get_items.register(list)
def _(obj):
    return enumerate(obj) # json array

def strip_whitespace(json_data):
    for key, value in get_items(json_data):
        if hasattr(value, 'strip'): # json string
            json_data[key] = value.strip()
        else:
            strip_whitespace(value) # recursive call


data = json.load(sys.stdin) # read json data from standard input
strip_whitespace(data)
json.dump(data, sys.stdout, indent=2)

注意:functools.singledispatch()函数(Python
3.4+)将允许使用collections
MutableMapping/MutableSequence代替dict/list此处。

输出量

{
  "anotherName": [
    {
      "anArray": [
        {
          "anotherKey": "value", 
          "key": "value"
        }, 
        {
          "anotherKey": "value", 
          "key": "value"
        }
      ]
    }
  ], 
  "name": [
    {
      "someKey": "some Value"
    }, 
    {
      "someKey": "another value"
    }
  ]
}
2020-07-27