Python解码JSON

2024-10-04 05:29:45 发布

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

我有以下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的范围是否足够宽,可以达到这个期望?


Tags: inidjsonobjfieldforstringtype
3条回答

我想应该是你创建了一个解码器,但永远不要告诉它^{}

使用:

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

试试看

obj = json.loads(jstr)

而不是

obj = json.JSONDecoder(jstr)

您似乎需要帮助迭代返回的对象,以及解码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))

相关问题 更多 >