#這是Python中的一個字典
dic = { 'str': 'this is a string', 'list': [1, 2, 'a', 'b'], 'sub_dic': { 'sub_str': 'this is sub str', 'sub_list': [1, 2, 3] }, 'end': 'end' }
//這是javascript中的一個JSON對象
json_obj = { 'str': 'this is a string', 'arr': [1, 2, 'a', 'b'], 'sub_obj': { 'sub_str': 'this is sub str', 'sub_list': [1, 2, 3] }, 'end': 'end' }
實際上JSON就是Python字典的字符串表示,但是字典作為一個復雜對象是無法直接轉換成定義它的代碼的字符串(不能傳遞所以需要將其轉換成字符串先),Python有一個叫simplejson的庫可以方便的完成JSON的生成和解析,這個包已經包含在Python2.6中,就叫json 主要包含四個方法: dump和dumps(從Python生成JSON),load和loads(解析JSON成Python的數據類型)dump和dumps的唯一區別是dump會生成一個類文件對象,dumps會生成字符串,同理load和loads分別解析類文件對象和字符串格式的JSON
import json dic = { 'str': 'this is a string', 'list': [1, 2, 'a', 'b'], 'sub_dic': { 'sub_str': 'this is sub str', 'sub_list': [1, 2, 3] }, 'end': 'end' } json.dumps(dic) #output: #'{"sub_dic": {"sub_str": "this is sub str", "sub_list": [1, 2, 3]}, "end": "end", "list": [1, 2, "a", "b"], "str": "this is a string"}'
新聞熱點
疑難解答