2011-03-23 63 views
3

我有以下的JSON: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程度?

回答

9

你似乎需要帮助遍历返回的对象,以及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)) 
+2

我会避开三重嵌套for循环。 – Blairg23 2014-12-09 22:52:26

+0

@ Blairg23你会怎么做,而不是通过已知格式的JSON进行处理? – Jeremy 2017-06-29 13:49:59

+1

@Jeremy如果您知道数据结构,只需引用键即可获取值。在这个例子中,当他只是说'slate_id_type = obj ['slate'] ['id'] ['type']''时,他使用了一个三重嵌套for循环。既然我们假设他将这些值用于某些事情,那么最好还是在那里宣布它们。无论如何,做得更清楚些。 – Blairg23 2017-06-30 00:19:25

9

尝试

obj = json.loads(jstr) 

,而不是

obj = json.JSONDecoder(jstr) 
+0

这是正确的做法。 'json.loads()'从JSON对象中返回一个Python字典。 – Blairg23 2014-12-09 22:51:42

3

我想这笔交易是您创建一个解码器,但它永远不会告诉decode()

用途:

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

好点。但: 邻在OBJ: \t \t打印(吨) \t \t 小号 升 一个 吨 Ë b 一个 Ñ Ñ Ê d:在邻 \t对于t – CoolStraw 2011-03-23 14:57:00

+1

对于你的JSON,Python将返回一个'dict'(字典)对象。默认情况下,迭代它将获得键,这是字符串。遍历一个字符串会得到你的字符。您可以使用'.iteritems()'获取'(key,value)'或者'.itervalues()'的元组来获取字典中for循环的值。 – Thanatos 2011-03-23 14:59:37

+1

@CoolStraw,decode()的结果是一个python字典。你可能会想通过o.items()迭代器,因为它是你遍历键,然后通过我修复的键 – 2011-03-23 14:59:52

1

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

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

无论如何,你应该遵循斯文的建议,并使用负载。

+0

中的字母。但我仍然无法浏览,因为我期待。我会更新我的问题 – CoolStraw 2011-03-23 14:57:22

2

JSONDecoder的签名是

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

,不接受在constructur JSON字符串。看看它的decode()方法。

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

2

这个工作很适合我,而且打印比通过对象Thanatos' answer明确循环一样简单:

import json 
from pprint import pprint 

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

pprint(obj) 

这里使用了“数据漂亮的打印机”(pprint)模块,文档可以找到它here