Python 解析 JSON

9 投票
6 回答
30029 浏览
提问于 2025-04-16 14:16

我有以下的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功能能满足这个期望吗?

6 个回答

4

我想说的是,你需要创建一个解码器,但别忘了调用它的 decode() 方法。

使用方法:

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

试试

obj = json.loads(jstr)

而不是

obj = json.JSONDecoder(jstr)
12

看起来你需要帮助来遍历返回的对象,以及解码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))

撰写回答