fork download
  1. import json
  2. import sys
  3. from collections import MutableMapping, MutableSequence
  4.  
  5. def strip_whitespace(json_data):
  6. if isinstance(json_data, MutableMapping): # json object
  7. it = json_data.items()
  8. elif isinstance(json_data, MutableSequence): # json array
  9. it = enumerate(json_data)
  10. else: # scalar data
  11. return # do nothing
  12.  
  13. for k, v in it:
  14. if hasattr(v, 'strip'): # json string
  15. json_data[k] = v.strip()
  16. else:
  17. strip_whitespace(v) # recursive call
  18.  
  19.  
  20. data = json.load(sys.stdin) # read json from stdin
  21. strip_whitespace(data)
  22. json.dump(data, sys.stdout, indent=2)
Success #stdin #stdout 0.1s 8888KB
stdin
{
    "name":[
        {
            "someKey": "\n\n   some Value   "
        },
        {
            "someKey": "another value    "
        }
    ],
    "anotherName":[
        {
            "anArray": [
                {
                    "key": "    value\n\n",
                    "anotherKey": "  value"
                },
                {
                    "key": "    value\n",
                    "anotherKey": "value"
                }
            ]
        }
    ]
}
stdout
{
  "anotherName": [
    {
      "anArray": [
        {
          "anotherKey": "value", 
          "key": "value"
        }, 
        {
          "anotherKey": "value", 
          "key": "value"
        }
      ]
    }
  ], 
  "name": [
    {
      "someKey": "some Value"
    }, 
    {
      "someKey": "another value"
    }
  ]
}