python中对json操作方法有两种,解码loads()和编码dumps()
简单来说:
import json
dicts = json.loads() #loads()方法,将json串解码为python对象,字典
json = json.dumps(dicts) #dumps()方法,将python字典编码为json串
简单例子:
>>> import json
>>> dicts = {'name':'test','type':[{'happy':'fish'},{'sad':'man'}]} #python的字典
>>> print(dicts.keys()) #python的字典可以通过内置的字典方法操作keys 和values
dict_keys(['type', 'name'])
>>> print(dicts['name'])
test
>>> print(dicts['type'][0]['happy'])
fish
>>> print(dicts['type'][1]['sad'])
man
>>> j = json.dumps(dicts) #通过dumps()方法,将python字典编码为json串
>>> j
'{"type": [{"happy": "fish"}, {"sad": "man"}], "name": "test"}'
>>> print(j['name']) #json不能通过字典方法获取keys 和 values了。
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
print(j['name'])
TypeError: string indices must be integers
更多的信息,可以参考python内部的json文档:
python>>> help(json)
或者官方文档:
http://docs.python.org/library/json.html#module-json