Python解析Json以及Python中字典和Json的區(qū)別
Python的字典和JSON在表現(xiàn)形式上非常相似
實(shí)際上JSON就是Python字典的字符串表示
但是字典作為一個復(fù)雜對象是無法直接轉(zhuǎn)換成定義它的代碼的字符串
Python有一個叫simplejson的庫可以方便的完成JSON的生成和解析
這個包已經(jīng)包含在Python2.6中
就叫json 主要包含四個方法:
dump和dumps(從Python生成JSON)
load和loads(解析JSON成Python的數(shù)據(jù)類型)
dump和dumps的唯一區(qū)別是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"}'
下面看下Python中字典和JS中Json的區(qū)別
這是Python中的一個字典
#這是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對象
//這是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' }
原文鏈接:Python解析Json以及Python中字典和Json的區(qū)別