首页 文章

使用Python将字符串转换为JSON

提问于
浏览
278

我对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"
                }
            }
        }
    }
}

但是当我打印dict(json)时,它会出错 .

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

4 回答

  • 17

    使用simplejson或cjson进行加速

    import simplejson as json
    
    json.loads(obj)
    
    or 
    
    cjson.decode(obj)
    
  • 76

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

    eval(your_json_format_string)

    例:

    >>> 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'>
    
  • 8

    json.loads()

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

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

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

相关问题