【问题标题】:Reading a Json response recursively with python使用python递归读取Json响应
【发布时间】:2012-05-19 10:07:19
【问题描述】:

我试图在不知道键名的情况下从 json 响应中打印所有“键、值”(例如,不使用语法 json['example'])。我正在使用使用 iteritems() 的递归函数来执行此操作,但我遇到了一些问题:

这是我试图阅读的 Json 响应:

{"servers": [{"id": "a059eccb-d929-43b2-8db3-b32b6201d60f", "links": [{"href": "http://192.168.100.142:8774/v2/2ad1fc162c254e59bea043560b7f73cb/servers/a059eccb-d929-43b2-8db3-b32b6201d60f", "rel": "self"}, {"href": "http://192.168.100.142:8774/2ad1fc162c254e59bea043560b7f73cb/servers/a059eccb-d929-43b2-8db3-b32b6201d60f", "rel": "bookmark"}], "name": "birk"}]}

这是我正在使用的功能:

def format_main_response(self, json_string):
    print "json:       " + json_string
    content = json.loads(str(json_string))
    for key, value in content.iteritems():
        print key
        if type(value) == type(['']):
            strg = str(json.dumps(value))
            strg = strg.strip('[]')
            self.format_main_response(strg)
        else:
            print value

我正在使用 strip 函数从我的 json 字符串中取出所有的 '[ ]'。如果我没有这样做,我会在尝试使用 'json.loads()' 函数加载它时出错。

 Traceback (most recent call last):
      File "main.py", line 135, in <module>
        formatter.format_main_response(nova_API.list_servers())
      File "/home/python/jsonformatter.py", line 51, in format_main_response
        self.format_main_response(strg, mod)
      File "/home/python/jsonformatter.py", line 51, in format_main_response
        self.format_main_response(strg, mod)
      File "/home/python/jsonformatter.py", line 31, in format_main_response
        for key, value in content.iteritems():
    AttributeError: 'list' object has no attribute 'iteritems'

我的问题是,在某些时候应该打印的 json 看起来像这样,没有 '[ ]':

{"href": "http://192.168.100.142:8774/v2/2ad1fc162c254e59bea043560b7f73cb/servers/a059eccb-d929-43b2-8db3-b32b6201d60f", "rel": "self"}, {"href": "http://192.168.100.142:8774/2ad1fc162c254e59bea043560b7f73cb/servers/a059eccb-d929-43b2-8db3-b32b6201d60f", "rel": "bookmark"}

当函数试图从这个 json 中找到 'key,value' 时,我得到了这个错误:

 Traceback (most recent call last): File "main.py", line 135, in <module>
    formatter.format_main_response(nova_API.list_servers())
  File "/home/python/jsonformatter.py", line 34, in format_main_response
    self.format_main_response(strg)
  File "/home/python/jsonformatter.py", line 34, in format_main_response
    self.format_main_response(strg)
  File "/home/python/jsonformatter.py", line 28, in format_main_response
    content = json.loads(str(json_string))
  File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 369, in decode
    raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 135 - line 1 column 273 (char 135 - 273)

在这种情况下我该怎么办?或者任何其他方式可以获得相同的结果?

【问题讨论】:

  • 太糟糕了,这个问题是一个非常复杂的提问方式:如何遍历 JSON。

标签: python json recursion


【解决方案1】:

下面的代码递归遍历 json 响应并打印键值对: 技巧是在main中只加载一次json响应,然后递归遍历响应:

def parse_json_response(content):

    if len (content.keys()) > 1 :
        for key, value in content.iteritems():
           print "key : ", key
           print "Value", value

            if type(value) is dict:
                parse_json_response(value)
    else:
        print value

if __name__ == '__main__':

    content = json.loads(str(response))
    parse_json_response(content)

希望对你有帮助。

【讨论】:

    【解决方案2】:

    怎么样:

    jsonStr = {"href": "http://192.168.100.142:8774/v2/2ad1fc162c254e59bea043560b7f73cb/servers/a059eccb-d929-43b2-8db3-b32b6201d60f", "rel": "self"}, {"href": "http://192.168.100.142:8774/2ad1fc162c254e59bea043560b7f73cb/servers/a059eccb-d929-43b2-8db3-b32b6201d60f", "rel": "bookmark"}
    print json.dumps(jsonStr, sort_keys=True, indent=2, separators=(',', ': '))
    

    这应该给你你想要的格式

    【讨论】:

      【解决方案3】:

      使用它:

      def format_main_response(json_string):
          print "json:       " + json_string
          content = json.loads(str(json_string))
          for key, value in content.iteritems():
              print key
              if type(value) == type(['']):
                  for sub_value in value:
                      strg = str(json.dumps(sub_value))
                      format_main_response(strg)
              else:
                  print value
      

      结果如下:

      ~$ python test_pdb.py 
      json:       {"servers": [{"id": "a059eccb-d929-43b2-8db3-b32b6201d60f", "links": [{"href": "http://192.168.100.142:8774/v2/2ad1fc162c254e59bea043560b7f73cb/servers/a059eccb-d929-43b2-8db3-b32b6201d60f", "rel": "self"}, {"href": "http://192.168.100.142:8774/2ad1fc162c254e59bea043560b7f73cb/servers/a059eccb-d929-43b2-8db3-b32b6201d60f", "rel": "bookmark"}], "name": "birk"}]}
      servers
      json:       {"id": "a059eccb-d929-43b2-8db3-b32b6201d60f", "links": [{"href": "http://192.168.100.142:8774/v2/2ad1fc162c254e59bea043560b7f73cb/servers/a059eccb-d929-43b2-8db3-b32b6201d60f", "rel": "self"}, {"href": "http://192.168.100.142:8774/2ad1fc162c254e59bea043560b7f73cb/servers/a059eccb-d929-43b2-8db3-b32b6201d60f", "rel": "bookmark"}], "name": "birk"}
      id
      a059eccb-d929-43b2-8db3-b32b6201d60f
      links
      json:       {"href": "http://192.168.100.142:8774/v2/2ad1fc162c254e59bea043560b7f73cb/servers/a059eccb-d929-43b2-8db3-b32b6201d60f", "rel": "self"}
      href
      http://192.168.100.142:8774/v2/2ad1fc162c254e59bea043560b7f73cb/servers/a059eccb-d929-43b2-8db3-b32b6201d60f
      rel
      self
      json:       {"href": "http://192.168.100.142:8774/2ad1fc162c254e59bea043560b7f73cb/servers/a059eccb-d929-43b2-8db3-b32b6201d60f", "rel": "bookmark"}
      href
      http://192.168.100.142:8774/2ad1fc162c254e59bea043560b7f73cb/servers/a059eccb-d929-43b2-8db3-b32b6201d60f
      rel
      bookmark
      name
      birk
      

      【讨论】:

        猜你喜欢
        • 2019-02-02
        • 2016-03-07
        • 1970-01-01
        • 2013-03-11
        • 1970-01-01
        • 2018-08-31
        • 1970-01-01
        • 1970-01-01
        • 2011-01-13
        相关资源
        最近更新 更多