Python的json模塊

python的Json模塊:
load 與 loads 都是用于encode編碼,將python數(shù)據(jù)(對(duì)象)轉(zhuǎn)換成json數(shù)據(jù)(對(duì)象)
dump 與 dumps 都是用于decode解碼,將json數(shù)據(jù)(對(duì)象)轉(zhuǎn)換成python數(shù)據(jù)(對(duì)象)

load 與 loads 和 dump 與 dumps 的區(qū)別:
load,dump類似,同樣都是操作文件句柄,比如本地有一個(gè)a.json文件名的json文件

    使用 json_file = json.load(open('a.json'))
    使用 json.dump(dict,open('a.json',"w"))將dict字典序列化為json對(duì)象存入到a.json文件當(dāng)中

loads,dumps類似,同樣都是操作內(nèi)存對(duì)象,

    loads將python數(shù)據(jù)轉(zhuǎn)化成json數(shù)據(jù)
    dumps將json數(shù)據(jù)轉(zhuǎn)化成python數(shù)據(jù)

數(shù)據(jù)轉(zhuǎn)換

    Decoder數(shù)據(jù)轉(zhuǎn)換:
    JSON    -->     Python
    object          dict
    array           list
    string          str
    number (int)    int
    number (real)   float
    true            True
    false           False
    null            None

    Encoder數(shù)據(jù)轉(zhuǎn)換:
    Python  -->         JSON
    dict                object
    list, tuple         array
    str                 string
    int, float, int-    numver
    float-derived Enums number
    True                true
    False               false
    None                null

序列化: 將數(shù)據(jù)結(jié)構(gòu)或?qū)ο筠D(zhuǎn)換成二進(jìn)制串的過(guò)程
反序列化:將在序列化過(guò)程中所生成的二進(jìn)制串轉(zhuǎn)換成數(shù)據(jù)結(jié)構(gòu)或者對(duì)象的過(guò)程

例子:
    # loads方法
    import json
    jsonData = '{"a":1,"b":2}';     ==>python利用type方法看到j(luò)sonData是str對(duì)象
    test = json.loads(jsonData)     ==>python利用type方法看到test的是dict字典對(duì)象
    print (test)
    print (test.get('b'))
    #結(jié)果
    {'b': 2, 'a': 1}
    2
    # dumps dump,load方法
    data = [{"a":"aaa","b":"bbb","c":[1,2,3,(4,5,6)]},33,'tantengvip',True]     ==>python的列表
    data1 = json.dumps(data)        ==>data1為字符串類型
    file = open('data.json','a')
    json.dump(data1,file)
    file.close()
    file1 = open('data.json','r')
    data2 = json.load(file1)
    print (data2)

json格式數(shù)據(jù)轉(zhuǎn)換存在第三方庫(kù):
Demjson
gitgub地址:
https://github.com/dmeranda/demjson

example:
>>> import demjson

>>> demjson.encode( ['one',42,True,None] )    # From Python to JSON
'["one",42,true,null]'

>>> demjson.decode( '["one",42,true,null]' )  # From JSON to Python
['one', 42, True, None]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容