解析JSON并在控制台

时间:2016-03-02 18:53:54

标签: python json dictionary recursion pretty-print

我有一个具有以下结构的JSON -

{
    "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"
                }
            ]
        }
    ]
}

我需要解析它并在控制台上显示,结构相同但没有“[]”和“{}”。

类似的东西:

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
       .......
   .........
.............

我尝试了pretty printing json

上提到的几个递归解决方案

但这没有成功。

可能有任何级别的数组和字典嵌套,我需要保留缩进并在控制台上打印它们。

有人可以指导我如何继续这个吗?

1 个答案:

答案 0 :(得分:0)

决定使用这个,并想出了一些可以打印出来的东西:

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

脚本是:

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)