【问题标题】:Inspecting json structure检查json结构
【发布时间】:2017-05-28 06:16:44
【问题描述】:

我正在尝试打印一些 json 的地图,以便我可以快速了解它的结构。我有一个函数可以递归地遍历嵌套的 json 并打印项目的所有键。但是,它的功能并不像我预期的那样。 example json

def inspect_json(level,nested_json):
    for key in nested_json.keys():
        print "{}.{}".format(level,key)
        if isinstance(nested_json[key],dict):
            level += 1
            inspect_json(level,nested_json[key])

>>> inspect_json(1,data)
1.@xmlns:aws
1.aws:OperationRequest
2.aws:RequestId
2.aws:UrlInfoResult
3.aws:Alexa
4.aws:ContentData
5.aws:DataUrl
6.@type
etc...

我希望输出看起来像这样:

>>> inspect_json(1,data)
aws:OperationRequest
  -aws:RequestId
aws:UrlInfoResult
  -aws:Alexa
    --aws:ContentData
    --aws:Related
    --aws:TrafficData
  -aws:ResponseStatus
    --@xmlns:aws
    --aws:StatusCode

【问题讨论】:

    标签: python json recursion


    【解决方案1】:

    我想你想要这样的东西:

    def inspect_json(level,nested_json):
        for key in nested_json.keys():
            print "{}.{}".format((level-1)*'  ',key)  # identation 2 blancs
            if isinstance(nested_json[key],dict):
                inspect_json(level+1,nested_json[key])  # increment level
    

    【讨论】:

      猜你喜欢
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 2013-03-14
      • 2015-04-11
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多