使用 Python 将 JSON 字符串转换为字典[重复]
- 2025-01-09 08:47:00
- admin 原创
- 78
问题描述:
我对 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"
}
}
}
}
}
但当我这样做时print(dict(json))
,出现错误。
我怎样才能将该字符串转换为结构,然后调用json["title"]
来获取"example glossary"
?
解决方案 1:
json.loads()
import json
d = json.loads(j)
print d['glossary']['title']
解决方案 2:
当我开始使用 json 时,我很困惑,有一段时间无法弄清楚,但最终我得到了我想要的,
这是简单的解决方案
import json
m = {'id': 2, 'name': 'hussain'}
n = json.dumps(m)
o = json.loads(n)
print(o['id'], o['name'])
解决方案 3:
如果您信任数据源,您可以使用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'>
解决方案 4:
使用 simplejson 或 cjson 来加速
import simplejson as json
json.loads(obj)
or
cjson.decode(obj)
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD