0

I have a JSON with the following structure -

{
    "gridDefinition": {},
    "zoneDefinitions": [
        {
            "status": "Pending",
            "name": "xxx-1",
            "globalName": "xxx-2",
            "id": 10,
            "memory": "1234",
            "cores": "0",
            "VM": [
                {
                    "ipAddress": "1.2.3.4",
                    "hostname": "zzzzz-1"
                },
                {
                    "ipAddress": "2.3.4.5",
                    "type": "virtual"
                }
            ]
        }
    ]
}

I need to parse this and display on the console, with the same structure but without all the "[]" and "{}" .

Something like:

gridDefinition:
zoneDefinitions:
   Status:Pending
   name:xxx-1
   id:10
   memory:1234
   cores:0
   VM:
      ipAddress : 1.2.3.4
      hostname : zzzzz-1

      ipAddress:2.3.4.5
       .......
   .........
.............

I tried a couple of recursive solutions mentioned on pretty printing json

But this didn't work out.

There could be any levels of nesting of arrays and dictionaries, I need to preserve the indentation and print them on the console.

Could anybody guide me how to proceed with this?

Community
  • 1
  • 1
  • You could just put the JSON in a dictionary, iterate over it, and print it out how you like - just like json.dumps does. – Jason De Arte Mar 02 '16 at 19:05
  • If you want to write json like data to a format without brackets but with meaningfull whitespace, try outputting it as YAML with e.g. [PyYAML](http://pyyaml.org/wiki/PyYAMLDocumentation). if you really just want the same structure ut without brackets, dump it to a string and search replace brackets with empty strings – Thijs D Mar 02 '16 at 20:40

1 Answers1

0

Decided to futz around with this, and came up with something that will print this:

gridDefinition:
zoneDefinitions:
    status: Pending
    name: xxx-1
    globalName: xxx-2
    id: 10
    memory: 1234
    cores: 0
    VM:
        ipAddress: 1.2.3.4
        hostname: zzzzz-1

        ipAddress: 2.3.4.5
        type: virtual

The script is:

import json
import sys
from collections import OrderedDict

indent = '  '

def crawl(n, i):
  s = ''
  if isinstance(n, dict):
    for (k,v) in n.items():
      if not isinstance(v, dict) and not isinstance(v, list):
        s += '{}{}: {}\n'.format(i*indent, k, str(v))
      else:
        s += '{}{}:\n{}'.format(i*indent, k, crawl(v, i+1))

  elif isinstance(n, list):
    was_complex = False
    for x in n:
      if not isinstance(x, dict) and not isinstance(x, list):
        s += '{}{}\n'.format(i*indent, str(x))
      else:
        if was_complex:
          s += '\n'
        s += crawl(x, i+1) # or, to flatten lists-of-lists, do not pass +1
        was_complex = isinstance(x, list) or isinstance(x, dict)

  return s

print crawl(json.load(sys.stdin, object_pairs_hook=OrderedDict), 0)
user2926055
  • 1,963
  • 11
  • 10