【发布时间】:2021-12-13 08:23:48
【问题描述】:
现在我有一个格式为 dict 的字符串,但我猜它是一个 json 格式,它看起来像:
{
"gid":"1201400250397201",
"memberships":[
"can be nested objects",
...
],
"name":"Name of task",
"parent":{
"gid":"1201400250397199",
"name":"name of parent task"
},
"permalink_url":"https://url...."
}
-
所以第一个问题:我说的对吗?我使用了 json 库中的
dumps(),但得到了 unicode 转义序列,loads()对我不起作用,我收到错误“JSON 对象必须是 str、bytes 或 bytearray,而不是 dict”。 -
第二个问题:如果不是 json 格式,我怎样才能获得舒适的视图?我做到了: 首先我得到 dict-line,然后我打印一个字典的键:
for key in task: task print(task[key])输出:
1201400250397201 [] Name of task {'gid': '1201400250397199', 'name': ''name of parent task'} https://url....
实际上,如果我得到这样的东西会很棒:
gid: 1201400250397201
name: Name of task
parent_name: 'Name of task' etc
但我不知道如何获得它:(
下一个问题:正如您在“父”部分(倒数第二行)中看到的那样,我还获得了字典,如何提取它并获得方便的格式? 或者,也许您有自己的舒适方法?
【问题讨论】:
-
Python 对象不是 JSON。为了漂亮地打印 Python 对象,请使用
pprint模块。 -
这能回答你的问题吗? How to pretty print nested dictionaries?
标签: json python-3.x dictionary