溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

python解析json字符串的方法

發(fā)布時(shí)間:2022-06-02 16:08:24 來(lái)源:億速云 閱讀:2384 作者:iii 欄目:大數(shù)據(jù)

這篇“python解析json字符串的方法”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來(lái)看看這篇“python解析json字符串的方法”文章吧。

json數(shù)據(jù)是一個(gè)輕量級(jí)的數(shù)據(jù)交換格式,采用完全獨(dú)立于語(yǔ)言的文本格式,這些特性使json稱(chēng)為理想的數(shù)據(jù)交換語(yǔ)言,易于人閱讀和編寫(xiě),同時(shí)易于機(jī)器解析和生成。

json中的字符集必須是UTF-8,json中的字符串必須用雙引號(hào)引起來(lái)。幾乎所有語(yǔ)言都內(nèi)置了解析json的庫(kù)。

python處理json的方法:

import json
# 字典類(lèi)型轉(zhuǎn)換為json字符串
data = {"id": 1, 'name': 'sy', 'passwrd': '123123'}

print(type(data))
json_str = json.dumps(data)
print(type(json_str))
print(json_str)

print("*" * 20)

# json字符串轉(zhuǎn)換為字典類(lèi)型
json_str2 = '{"programers":[ {"firstName":"Breet","lastName":"MMM","email":"XXX"},'\
            '{"firstName":"Breet","lastName":"MMM","email":"XXX"}], ' \
            '"author": [{"firstName": "su", "lastName": "yang", "email": "XXX"},'\
            '{"firstName": "Breet", "lastName": "MMM", "email": "XXX"}]}'

print(type(json_str2))

data2 = json.loads(json_str2)

print(type(data2))
print(json_str2)
print(data2)

print('*' * 20)

# 將json數(shù)據(jù)寫(xiě)入文件,用文件傳送

with open('aaa.json', 'w') as f:
    json.dump(data, f)

with open('aaa.json', 'r') as f:
    data3 = json.load(f)
    print(type(data3))
    print(data3)

python處理json數(shù)據(jù)使用的兩個(gè)函數(shù):

  • json.dumps:將 Python 對(duì)象編碼成 JSON 字符串    

  • json.loads:將已編碼的 JSON 字符串解碼為 Python 對(duì)象    

注意:使用 JSON 函數(shù)需要導(dǎo)入 json 庫(kù):import json。

以上就是關(guān)于“python解析json字符串的方法”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI