解析JSON并在cons上打印内容

2024-09-19 23:28:17 发布

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

我有一个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上提到的几个递归解决方案

但这没有成功。你知道吗

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

有人能告诉我怎么做吗?你知道吗


Tags: nameidjsonstatusvm结构coreshostname
1条回答
网友
1楼 · 发布于 2024-09-19 23:28:17

我决定把这本书翻个底朝天,然后想出一个可以打印这本书的东西:

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)

相关问题 更多 >