19

I have a JSON file that has the following structure:

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

Now I want to strip off all he whitespaces and newlines for every value in the JSON file. Is there some way to iterate over each element of the dictionary and the nested dictionaries and lists?

3 Answers 3

11

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

Using pkgutil.simplegeneric() to create a helper function 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)

Note: functools.singledispatch() function (Python 3.4+) would allow to use collections' MutableMapping/MutableSequence instead of dict/list here.

Output

{
  "anotherName": [
    {
      "anArray": [
        {
          "anotherKey": "value", 
          "key": "value"
        }, 
        {
          "anotherKey": "value", 
          "key": "value"
        }
      ]
    }
  ], 
  "name": [
    {
      "someKey": "some Value"
    }, 
    {
      "someKey": "another value"
    }
  ]
}
2
  • What if instead of using sys, I'd want to clean a file, meaning read from it and write back to a new json file? I somehow can't get it working. sys.stdin / sys.stdout is so alien to me and I feel like your solution is specifically designed to work with it alone.
    – blkpingu
    Jan 2, 2020 at 15:12
  • @TobiasKolb sys.stdin, sys.stdout are ordinary file objects by default (exactly the type of objects that are returned by the builtin open() function) i.e., if you know how to work with files in Python, you know how to work with sys.stdin/sys.stdout. Though you don't need to modify the source to read json data from a file and write the result to a new file: < input.json ./script-from-the-answer > output.json
    – jfs
    Jan 5, 2020 at 19:30
6

Parse the file using JSON:

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

then walk through the resulting data structure.

2
  • 1
    This won't work: The newlines are actually the characters \ and n, so you need to replace \\n with ''. Also, this won't remove the white space.
    – Owen
    Jun 14, 2013 at 0:36
  • 2
    You can customize the "cleanup" line as needed. My version of Python cleaned up the white space just fine. You can clean up the values as you walk through 'data'. Jun 14, 2013 at 4:19
2

This may not be the most efficient process, but it works. I copied that sample into a file named json.txt, then read it, deserialized it with json.loads(), and used a pair of functions to recursively clean it and everything inside it.

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

The result...

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'}]}
5
  • 1
    don't use eval() for json text. You could use json.loads() instead
    – jfs
    Jun 14, 2013 at 5:33
  • You probably also want to strip values in a list (else clause is missing in clean_list()). "".join(f.readlines()) should be just f.read() or you could pass a file object directly json.load(f). value.replace("\\n", "") is incorrect: "\n" - newline, "\\n" - two chars; anyway .strip() removes any leading/trailing whitespace including newlines. The copying d.items() and l[:] seems unnecessary.
    – jfs
    Jun 14, 2013 at 15:28
  • Thanks for the additional tips. I've updated the code again. FWIW, I originally had an else clause in clean_list() for cleaning individual list items, but as the sample JSON data didn't use it, I took it out before posting my original answer. Jun 14, 2013 at 18:43
  • +1: it looks ok now. Note: l[index] == item so you could use item as rvalue instead of l[index]. To close a file automatically, you could use with open(filename) as file: ... it will close the file even if an exception occurs.
    – jfs
    Jun 15, 2013 at 6:46
  • Thanks. Will fix the l[index] issue now. Not sure how I didn't catch that one myself. Regarding with, I've been under the impression for who-knows-how-long that it only worked in Python 3+. Just searched and found that it was added in 2.5. Not sure where my memory is pulling the 3+ reference from, but I'll fix that as well. Thanks much for the instruction! Jun 15, 2013 at 19:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.