溫馨提示×

溫馨提示×

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

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

如何在Python3項(xiàng)目中實(shí)現(xiàn)一個(gè)字典、列表和json對象的轉(zhuǎn)換功能

發(fā)布時(shí)間:2021-02-24 16:30:33 來源:億速云 閱讀:181 作者:戴恩恩 欄目:開發(fā)技術(shù)

這篇文章主要介紹了如何在Python3項(xiàng)目中實(shí)現(xiàn)一個(gè)字典、列表和json對象的轉(zhuǎn)換功能,此處通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考價(jià)值,需要的朋友可以參考下:

Python主要用來做什么

Python主要應(yīng)用于:1、Web開發(fā);2、數(shù)據(jù)科學(xué)研究;3、網(wǎng)絡(luò)爬蟲;4、嵌入式應(yīng)用開發(fā);5、游戲開發(fā);6、桌面應(yīng)用開發(fā)。

python3可以使用json模塊操作json

json.dumps(): 對json進(jìn)行編碼,對應(yīng)php的json_encode()

json.loads(): 對json進(jìn)行解碼,對應(yīng)php的json_decode()

test.py

#!/usr/bin/python3
import json
#python字典類型轉(zhuǎn)換為json對象
data = {
  'id' : 1,
  'name' : 'test1',
  'age' : '1'
}
data2 = [{
  'id' : 1,
  'name' : 'test1',
  'age' : '1'
},{
  'id' : 2,
  'name' : 'test2',
  'age' : '2'
}]
json_str = json.dumps(data)
print ("python原始數(shù)據(jù):", repr(data))
print ("json對象:", json_str)
json_str2 = json.dumps(data2)
print ("python原始數(shù)據(jù):", repr(data2))
print ("json對象:", json_str2)
# 將json對象轉(zhuǎn)換為python字典
data3 = json.loads(json_str)
print ("data3['name']: ", data3['name'])
print ("data3['age']: ", data3['age'])

執(zhí)行結(jié)果

[root@mail pythonCode]# python3 test.py
python原始數(shù)據(jù): {'id': 1, 'name': 'test1', 'age': '1'}
json對象: {"id": 1, "name": "test1", "age": "1"}
python原始數(shù)據(jù): [{'id': 1, 'name': 'test1', 'age': '1'}, {'id': 2, 'name': 'test2', 'age': '2'}]
json對象: [{"id": 1, "name": "test1", "age": "1"}, {"id": 2, "name": "test2", "age": "2"}]
data3['name']:  test1
data3['age']:  1

到此這篇關(guān)于如何在Python3項(xiàng)目中實(shí)現(xiàn)一個(gè)字典、列表和json對象的轉(zhuǎn)換功能的文章就介紹到這了,更多相關(guān)如何在Python3項(xiàng)目中實(shí)現(xiàn)一個(gè)字典、列表和json對象的轉(zhuǎn)換功能的內(nèi)容請搜索億速云以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持億速云!

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

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

AI