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

2024-06-24 13:20:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个具有以下结构的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文件中每个值的所有空白和换行符。有什么方法可以遍历字典的每个元素以及嵌套的字典和列表吗?


Tags: 文件keynamejson字典valueanothersome
3条回答

这可能不是最有效的过程,但它是有效的。我将该示例复制到名为json.txt的文件中,然后读取它,用json.loads()反序列化它,并使用一对函数递归地清理它及其内部的所有内容。

import json

def clean_dict(d):
    for key, value in d.iteritems():
        if isinstance(value, list):
            clean_list(value)
        elif isinstance(value, dict):
            clean_dict(value)
        else:
            newvalue = value.strip()
            d[key] = newvalue

def clean_list(l):
    for index, item in enumerate(l):
        if isinstance(item, dict):
            clean_dict(item)
        elif isinstance(item, list):
            clean_list(item)
        else:
            l[index] = item.strip()

# Read the file and send it to the dict cleaner
with open("json.txt") as f:
    data = json.load(f)

print "before..."
print data, "\n"

clean_dict(data)

print "after..."
print data

结果。。。

before...
{u'anotherName': [{u'anArray': [{u'anotherKey': u'  value', u'key': u'    value\n\n'}, {u'anotherKey': u'value', u'key': u'    value\n'}]}], u'name': [{u'someKey': u'\n\n   some Value   '}, {u'someKey': u'another value    '}]} 

after...
{u'anotherName': [{u'anArray': [{u'anotherKey': u'value', u'key': u'value'}, {u'anotherKey': u'value', u'key': u'value'}]}], u'name': [{u'someKey': u'some Value'}, {u'someKey': u'another value'}]}

Now I want to strip off all he whitespaces and newlines for every value in the JSON file

使用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)

注意:^{}函数(Python 3.4+)允许在这里使用collections'^{},而不是dict/list

Output

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

使用JSON分析文件:

import json
file = file.replace('\n', '')    # do your cleanup here
data = json.loads(file)

然后遍历生成的数据结构。

相关问题 更多 >