如何在 Python 中将 JSON 字符串转换为字典?

Posted

技术标签:

【中文标题】如何在 Python 中将 JSON 字符串转换为字典?【英文标题】:How convert a JSON string to Dictionary in Python? 【发布时间】:2017-08-11 21:47:02 【问题描述】:

我已经阅读了关于从 str 到 dic 的 python 转换的不同帖子,但我仍然遇到问题,我无法在字典中转换我的 str。

这是我的原始字符串:

"faqId":1,"isPrivate":false,"question":"Question 1","answer":"# Hello world!!\r\n\r\n*   Proin elementum sollicitudin sodales.\r\n*   Nam id erat nec nibh dictum cursus.\r\n\r\n> In et urna eros. Fusce molestie, orci vel laoreet tempus, sem justo blandit magna, at volutpat velit lacus id turpis.  \r\n> Quisque malesuada sem at interdum congue. Aenean dapibus fermentum orci eu euismod.\r\n\r\n![](http://onehungrymind.com/wp-content/uploadspng)\r\n\r\n[This is an example link to nothing]()\r\n","faqId":2,"isPrivate":false,"question":"Question 2","answer":"Dillinger\r\n=========\r\n\r\nDillinger is a cloud-enabled html5 Markdown editor.\r\n\r\n  - Type some Markdown text in the left window\r\n  - See the HTML in the right\r\n  - Magic\r\n\r\nMarkdown is a lightweight markup language based on the formatting conventions that people naturally use in email.  As [John Gruber] writes on the [Markdown site] [1]:\r\n\r\n> The overriding design goal for Markdown's\r\n> formatting syntax is to make it as readable \r\n> as possible. The idea is that a\r\n> Markdown-formatted document should be\r\n> publishable as-is, as plain text, without\r\n> looking like it's been marked up with tags\r\n> or formatting instructions.\r\n\r\nThis text you see here is *actually* written in Markdown! To get a feel for Markdown's syntax, type some text into the left window and watch the results in the right.  \r\n\r\nVersion\r\n----\r\n\r\n2.0\r\n\r\nTech\r\n-----------\r\n\r\nDillinger uses a number of open source projects to work properly:\r\n\r\n* [Ace Editor] - awesome web-based text editor\r\n* [Marked] - a super fast port of Markdown to javascript\r\n* [Twitter Bootstrap] - great UI boilerplate for modern web apps\r\n* [node.js] - evented I/O for the backend\r\n* [Express] - fast node.js network app framework [@tjholowaychuk]\r\n* [keymaster.js] - awesome keyboard handler lib by [@thomasfuchs]\r\n* [jQuery] - duh \r\n\r\nInstallation\r\n--------------\r\n\r\n```sh\r\ngit clone [git-repo-url] dillinger\r\ncd dillinger\r\nnpm i -d\r\nmkdir -p public/files/md,html,pdf\r\n```\r\n\r\n##### Configure Plugins. Instructions in following README.md files\r\n\r\n* plugins/dropbox/README.md\r\n* plugins/github/README.md\r\n* plugins/googledrive/README.md\r\n\r\n```sh\r\nnode app\r\n```\r\n\r\n\r\nLicense\r\n----\r\n\r\nMIT\r\n\r\n\r\n**Free Software, Hell Yeah!**\r\n\r\n[john gruber]:http://daringfireball.net/\r\n[@thomasfuchs]:http://twitter.com/thomasfuchs\r\n[1]:http://daringfireball.net/projects/markdown/\r\n[marked]:https://github.com/chjj/marked\r\n[Ace Editor]:http://ace.ajax.org\r\n[node.js]:http://nodejs.org\r\n[Twitter Bootstrap]:http://twitter.github.com/bootstrap/\r\n[keymaster.js]:https://github.com/madrobby/keymaster\r\n[jQuery]:http://jquery.com\r\n[@tjholowaychuk]:http://twitter.com/tjholowaychuk\r\n[express]:http://expressjs.com\r\n","faqId":4,"isPrivate":false,"question":"Question 3","answer":"# Markdown Test\r\nThis is a link: [PDF link]"

我试着整理一下

replace("false","False")
replace("true","True")
replace('"',"'")

所以我回来了:

'faqId':1,'isPrivate':False,'question':'Question 1','answer':'# Hello world!!\r\n\r\n*   Proin elementum sollicitudin sodales.\r\n*   Nam id erat nec nibh dictum cursus.\r\n\r\n> In et urna eros. Fusce molestie, orci vel laoreet tempus, sem justo blandit magna, at volutpat velit lacus id turpis.  \r\n> Quisque malesuada sem at interdum congue. Aenean dapibus fermentum orci eu euismod.\r\n\r\n![](http://onehungrymind.com/wp-content/uploads.png)\r\n\r\n[This is an example link to nothing]()\r\n','faqId':2,'isPrivate':False,'question':'Question 2','answer':'Dillinger\r\n=========\r\n\r\nDillinger is a cloud-enabled HTML5 Markdown editor.\r\n\r\n  - Type some Markdown text in the left window\r\n  - See the HTML in the right\r\n  - Magic\r\n\r\nMarkdown is a lightweight markup language based on the formatting conventions that people naturally use in email.  As [John Gruber] writes on the [Markdown site] [1]:\r\n\r\n> The overriding design goal for Markdown's\r\n> formatting syntax is to make it as readable \r\n> as possible. The idea is that a\r\n> Markdown-formatted document should be\r\n> publishable as-is, as plain text, without\r\n> looking like it's been marked up with tags\r\n> or formatting instructions.\r\n\r\nThis text you see here is *actually* written in Markdown! To get a feel for Markdown's syntax, type some text into the left window and watch the results in the right.  \r\n\r\nVersion\r\n----\r\n\r\n2.0\r\n\r\nTech\r\n-----------\r\n\r\nDillinger uses a number of open source projects to work properly:\r\n\r\n* [Ace Editor] - awesome web-based text editor\r\n* [Marked] - a super fast port of Markdown to JavaScript\r\n* [Twitter Bootstrap] - great UI boilerplate for modern web apps\r\n* [node.js] - evented I/O for the backend\r\n* [Express] - fast node.js network app framework [@tjholowaychuk]\r\n* [keymaster.js] - awesome keyboard handler lib by [@thomasfuchs]\r\n* [jQuery] - duh \r\n\r\nInstallation\r\n--------------\r\n\r\n```sh\r\ngit clone [git-repo-url] dillinger\r\ncd dillinger\r\nnpm i -d\r\nmkdir -p public/files/md,html,pdf\r\n```\r\n\r\n##### Configure Plugins. Instructions in following README.md files\r\n\r\n* plugins/dropbox/README.md\r\n* plugins/github/README.md\r\n* plugins/googledrive/README.md\r\n\r\n```sh\r\nnode app\r\n```\r\n\r\n\r\nLicense\r\n----\r\n\r\nMIT\r\n\r\n\r\n**Free Software, Hell Yeah!**\r\n\r\n[john gruber]:http://daringfireball.net/\r\n[@thomasfuchs]:http://twitter.com/thomasfuchs\r\n[1]:http://daringfireball.net/projects/markdown/\r\n[marked]:https://github.com/chjj/marked\r\n[Ace Editor]:http://ace.ajax.org\r\n[node.js]:http://nodejs.org\r\n[Twitter Bootstrap]:http://twitter.github.com/bootstrap/\r\n[keymaster.js]:https://github.com/madrobby/keymaster\r\n[jQuery]:http://jquery.com\r\n[@tjholowaychuk]:http://twitter.com/tjholowaychuk\r\n[express]:http://expressjs.com\r\n','faqId':4,'isPrivate':False,'question':'Question 3','answer':'# Markdown Test\r\nThis is a link: [PDF link]'

我正在尝试不同的方法:

import json
json.loads(MY_STR)

import ast
ast.literal_eval(MY_STR)

等等……

但是他们都给我一些错误,你能帮帮我吗?

【问题讨论】:

非常感谢,成功了 只是为进一步的读者澄清事情,你的字符串中有多个字典的问题。这就是为什么 json 和 ast 都不起作用的原因。在所有内容周围添加括号都有效,因为它将所有字典组合到一个列表中。 【参考方案1】:

方括号将原始字符串括起来,使其成为有效的JSON字符串:

import json

valid_json_string = "[" + your_string + "]"  # or "[0]".format(your_string)
data = json.loads(valid_json_string)

【讨论】:

以上是关于如何在 Python 中将 JSON 字符串转换为字典?的主要内容,如果未能解决你的问题,请参考以下文章

如何在python中将字符串列表转换为格式正确的json? [复制]

如何在 Python 中将代理对转换为普通字符串?

在 Python 中将 OrderedDict 的字符串转换为 JSON

如何在python3.6中将字符串转换为唯一的整数,反之亦然(在0到255之间)

如何在python中将JSON转换为数据框

如何在python中将json转换为csv?