【问题标题】:Python decodes JSONPython 解码 JSON
【发布时间】:2011-07-21 09:27:55
【问题描述】:

我有以下 json:

{
    "slate" : {
        "id" : {
            "type" : "integer"
        },
        "name" : {
            "type" : "string"
        },
        "code" : {
            "type" : "integer",
            "fk" : "banned.id"
        }
    },
    "banned" : {
        "id" : {
            "type" : "integer"
        },
        "domain" : {
            "type" : "string"
        }
    }
}

我想找出最佳解码方式,以便对其进行易于浏览的 python 对象表示。

我试过了:

import json

jstr = #### my json code above #### 
obj = json.JSONDecoder().decode(jstr)

for o in obj:
  for t in o: 
    print (o)

但我明白了:

    f       
    s
    l
    a
    t
    e
    b
    a
    n
    n
    e
    d

我不明白这是怎么回事。理想的情况是一棵树(甚至是一个以树的方式组织的列表),我可以以某种方式浏览它:

for table in myList:
    for field in table:
         print (field("type"))
         print (field("fk"))  

Python 的内置 JSON API 范围是否足以达到这一预期?

【问题讨论】:

    标签: python json python-3.x


    【解决方案1】:

    您似乎需要帮助迭代返回的对象,以及解码 JSON。

    import json
    
    #jstr = "... that thing above ..."
    # This line only decodes the JSON into a structure in memory:
    obj = json.loads(jstr)
    # obj, in this case, is a dictionary, a built-in Python type.
    
    # These lines just iterate over that structure.
    for ka, va in obj.iteritems():
        print ka
        for kb, vb in va.iteritems():
            print '  ' + kb
            for key, string in vb.iteritems():
                print '    ' + repr((key, string))
    

    【讨论】:

    • @Blairg23 你会做什么来处理已知格式的 JSON?
    • @Jeremy 如果您知道数据结构,只需引用键即可获取值。在这个例子中,他使用了一个三重嵌套的 for 循环,而他可以说类似这样的话:slate_id_type = obj['slate']['id']['type']。由于我们假设他将这些值用于某事,因此不妨在此处声明它们。无论如何要明确得多。
    • @Jeremy 绝对!顺便说一句,不要忘记放置tryexcept 块以捕获任何可能不存在的键值。查看docs.python.org/3.6/library/exceptions.html(如果您正在使用,请更改为 2.7)以获取更多例外选项。
    【解决方案2】:

    试试

    obj = json.loads(jstr)
    

    而不是

    obj = json.JSONDecoder(jstr)
    

    【讨论】:

    • 这是正确的做法。 json.loads() 从 JSON 对象返回一个 Python 字典。
    【解决方案3】:

    我猜的交易是你创建一个解码器,但永远不要告诉decode()

    用途:

    o = json.JSONDecoder().decode(jstr)
    

    【讨论】:

    • 好点。但是: for o in obj: for t in o: print(t) s l a t e b a n n e d
    • 对于您的 JSON,Python 将返回一个 dict(字典)对象。默认情况下,迭代它会得到键,它们是字符串。遍历字符串可以获得字符。您可以使用 .iteritems() 获取 (key, value) 的元组,或使用 .itervalues() 获取字典中 for 循环中的值。
    • @CoolStraw,decode() 的结果是一个python字典。您可能希望迭代 o.items(),因为您正在迭代键,然后迭代键中的字母
    【解决方案4】:

    JSONDecoder 的签名是

    class json.JSONDecoder([encoding[, object_hook[, parse_float[, parse_int[, 
        parse_constant[, strict[, object_pairs_hook]]]]]]])
    

    并且不接受构造函数中的 JSON 字符串。看看它的 decode() 方法。

    http://docs.python.org/library/json.html#json.JSONDecoder

    【讨论】:

      【解决方案5】:

      这对我来说效果很好,而且打印比像Thanatos' answer 中那样显式循环对象更简单:

      import json
      from pprint import pprint
      
      jstr = #### my json code above #### 
      obj = json.loads(jstr)
      
      pprint(obj)
      

      这使用“Data Pretty Printer”(pprint)模块,可以在here找到其文档。

      【讨论】:

        【解决方案6】:

        您在示例中提供的字符串不是有效的 JSON。

        两个右花括号之间的最后一个逗号是非法的。

        不管怎样,你应该听从 Sven 的建议,改用 load。

        【讨论】:

        • 我修好了。但我仍然无法按预期浏览。我要更新我的问题
        猜你喜欢
        • 2016-11-09
        • 1970-01-01
        • 2014-01-19
        • 1970-01-01
        • 1970-01-01
        • 2013-04-07
        • 2010-10-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多