Python 解码 JSON
我有以下 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 范围是否足够宽以达到此期望?
I've the following json:
{
"slate" : {
"id" : {
"type" : "integer"
},
"name" : {
"type" : "string"
},
"code" : {
"type" : "integer",
"fk" : "banned.id"
}
},
"banned" : {
"id" : {
"type" : "integer"
},
"domain" : {
"type" : "string"
}
}
}
I'd like to figure out the best decoding way to have an easily browsable python object presentation of it.
I tried:
import json
jstr = #### my json code above ####
obj = json.JSONDecoder().decode(jstr)
for o in obj:
for t in o:
print (o)
But I get:
f
s
l
a
t
e
b
a
n
n
e
d
And I don't understand what's the deal. The ideal would be a tree (even a list organized in a tree way) that I could browse somehow like:
for table in myList:
for field in table:
print (field("type"))
print (field("fk"))
Is the Python's built-in JSON API extent wide enough to reach this expectation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您似乎需要帮助迭代返回的对象以及解码 JSON。
You seem to need help iterating over the returned object, as well as decoding the JSON.
尝试
代替
Try
instead of
我猜想的交易是您创建一个解码器,但永远不要告诉它 <代码>解码()。
使用:
The deal I guess is that you create a decoder, but never tell it to
decode()
.Use:
JSONDecoder 的签名是
且不接受构造函数中的 JSON 字符串。看看它的decode()方法。
http://docs.python.org/library/json.html#json.JSONDecoder
The signature of JSONDecoder is
and does not accept the JSON string in the constructur. Look at its decode() method.
http://docs.python.org/library/json.html#json.JSONDecoder
这对我来说效果很好,而且打印比显式循环对象更简单,如 Thanatos 的答案:
这使用“Data Pretty Printer”(
pprint
) 模块,其文档可以在 此处。This worked well for me, and the printing is simpler than explicitly looping through the object like in Thanatos' answer:
This uses the "Data Pretty Printer" (
pprint
) module, the documentation for which can be found here.您在示例中提供的字符串不是有效的 JSON。
两个右大括号之间的最后一个逗号是非法的。
无论如何,你应该遵循 Sven 的建议并使用负载。
The String you provide in the example is not valid JSON.
The last comma between two closing curly braces is illegal.
Anyway you should follow Sven's suggestion and use loads instead.