使用 Python 将 JSON 字符串转换为 dict

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4528099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:08:35  来源:igfitidea点击:

Convert JSON string to dict using Python

pythonjsonstring

提问by Frias

I'm a little bit confused with JSON in Python. To me, it seems like a dictionary, and for that reason I'm trying to do that:

我对 Python 中的 JSON 有点困惑。对我来说,它似乎是一本字典,因此我试图这样做:

{
    "glossary":
    {
        "title": "example glossary",
        "GlossDiv":
        {
            "title": "S",
            "GlossList":
            {
                "GlossEntry":
                {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef":
                    {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

But when I do print dict(json), it gives an error.

但是当我这样做时print dict(json),它会出错。

How can I transform this string into a structure and then call json["title"]to obtain "example glossary"?

如何将此字符串转换为结构,然后调用json["title"]以获取“示例词汇表”?

采纳答案by Ignacio Vazquez-Abrams

json.loads()

json.loads()

import json

d = json.loads(j)
print d['glossary']['title']

回答by locojay

use simplejson or cjson for speedups

使用 simplejson 或 cjson 进行加速

import simplejson as json

json.loads(obj)

or 

cjson.decode(obj)

回答by Hussain

When I started using json, I was confused and unable to figure it out for some time, but finally I got what I wanted
Here is the simple solution

当我开始使用json时,我很困惑,有一段时间无法弄清楚,但最终我得到了我想要的
这里是简单的解决方案

import json
m = {'id': 2, 'name': 'hussain'}
n = json.dumps(m)
o = json.loads(n)
print(o['id'], o['name'])

回答by kakhkAtion

If you trust the data source, you can use evalto convert your string into a dictionary:

如果您信任数据源,则可以使用eval将您的字符串转换为字典:

eval(your_json_format_string)

eval(your_json_format_string)

Example:

例子:

>>> x = "{'a' : 1, 'b' : True, 'c' : 'C'}"
>>> y = eval(x)

>>> print x
{'a' : 1, 'b' : True, 'c' : 'C'}
>>> print y
{'a': 1, 'c': 'C', 'b': True}

>>> print type(x), type(y)
<type 'str'> <type 'dict'>

>>> print y['a'], type(y['a'])
1 <type 'int'>

>>> print y['a'], type(y['b'])
1 <type 'bool'>

>>> print y['a'], type(y['c'])
1 <type 'str'>