python 处理 json 主要是 json.dumps()、json.loads()、json.dump() 和 json.load() 四个。
json.dumps()、json.loads() 处理的对象是在python中的 dict 或 str。而 json.dump() 和 json.load() 则是直接处理 json 文件。
加载:
import json
将 dict 转为 str 使用的是 json.dumps()
>>> json_obj = {\"class\": 1, \"id\": 1, \"uri\": \"http:xxxx\"}
>>> str_example = json.dumps(json_obj)
>>> print str_example
>>> print type(str_example)
{\"class\": 1, \"id\": 1, \"uri\": \"http:xxxx\"}
<type \'str\'>
将 str 转为 dict 使用的是 json.loads()
>>> str_example = \'{\"class\": 1, \"id\": 1, \"uri\": \"http:xxxx\"}\'
>>> json_obj = json.loads(str_example)
>>> print json_obj
>>> print type(json_obj)
{u\'uri\': u\'http:xxxx\', u\'class\': 1, u\'id\': 1}
<type \'dict\'>
且此时输出的dict中的字符串为unicode编码
直接将 dict 保存成 json格式文件,json.dump()
>>> json_obj = {\"class\": 1, \"id\": 1, \"uri\": \"http:xxxx\"}
>>> json_file_path = \'./example.json\'
>>> json.dump(json_obj, open(json_file_path, \'w\'))
直接从 json格式文件中加载 json数据,json.load()
>>> json_file_path = \'./example.json\'
>>> json_obj = json.load(open(json_file_path, \'r\'))
>>> print json_obj
>>> print type(json_obj)
{u\'uri\': u\'http:xxxx\', u\'class\': 1, u\'id\': 1}
<type \'dict\'> 版权声明
本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。



