什么是JSON?
网上对JSON有很多教程,有各种各样的解释。一言以蔽之,JSON本质上是一种语法,这种语法的作用是把数据以字符串的形式存储、传递,多用于Web编程。
JSON的典型示例
'{
"employees": [
{ "firstName":"Bill" , "lastName":"Gates" },
{ "firstName":"George" , "lastName":"Bush" },
{ "firstName":"Thomas" , "lastName":"Carter" }
]
}'
从Python的角度理解JSON,JSON的主要构成要素只有两个:字典,字符串。大家可以把JSON理解为字符串化的字典。
以上面的典型示例为例子,"employees"为key, 后面的由3个字典组成的列表就为Value. 这就构成了一份JSON数据.
利用Packge json解析、生成JSON
利用json的loads和dumps两个函数,基本可以满足需求。我们假设上述JSON典型示例字符串为Json_str,话不多说,直接上代码:
>>> import json
>>> Json_afterdecode = json.loads(Json_str)
>>> print(type(Json_afterdecode))
<class 'dict'>
>>> Json_afterdecode
{'employees': [{'lastName': 'Gates', 'firstName': 'Bill'}, {'lastName': 'Bush', 'firstName': 'George'}, {'lastName': 'Carter', 'firstName': 'Thomas'}]}
>>> Json_afterdecode["employees"][0]["lastName"]
'Gates'
>>> Json_afterencode = json.dumps(Json_afterdecode)
>>> print(type(Json_afterencode))
<class 'str'>
>>> Json_afterencode
'{"employees": [{"lastName": "Gates", "firstName": "Bill"}, {"lastName": "Bush", "firstName": "George"}, {"lastName": "Carter", "firstName": "Thomas"}]}'
优雅的输出
很多时候我们需要把JSON放到文件里,变成JSON文件(比如需要用JSON文件存储一些配置信息时),但是一行字符串丑的不行,怎么办?
json.dumps(<你要转换为JSON的data>, sort_keys=True, indent=4)),可以实现排序和缩进
>>> Json_afterencode_elegant = json.dumps(Json_afterdecode, sort_keys=True, indent=4)
>>> print(Json_afterencode_elegant)
{
"employees": [
{
"firstName": "Bill",
"lastName": "Gates"
},
{
"firstName": "George",
"lastName": "Bush"
},
{
"firstName": "Thomas",
"lastName": "Carter"
}
]
}
瞧,这样不仅看起来美观,也便于其他人往Json里填充数据。
当我们需要从JSON文件里读取信息时,直接用下面的路径就能直接得到JSON数据了。
>>> Json_afterdecode = json.loads(open("JSON文件路径","r").read())
参考链接:
RUNOOB的JSON教程: http://www.runoob.com/json/json-tutorial.html