日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Python3JSON數(shù)據(jù)解析

Python3 JSON 數(shù)據(jù)解析

JSON (JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式。

創(chuàng)新互聯(lián)公司網(wǎng)站建設(shè)公司一直秉承“誠信做人,踏實做事”的原則,不欺瞞客戶,是我們最起碼的底線! 以服務(wù)為基礎(chǔ),以質(zhì)量求生存,以技術(shù)求發(fā)展,成交一個客戶多一個朋友!專注中小微企業(yè)官網(wǎng)定制,網(wǎng)站建設(shè)、成都網(wǎng)站制作,塑造企業(yè)網(wǎng)絡(luò)形象打造互聯(lián)網(wǎng)企業(yè)效應(yīng)。

如果你還不了解 JSON,可以先閱讀我們的 。

Python3 中可以使用 json 模塊來對 JSON 數(shù)據(jù)進行編解碼,它包含了兩個函數(shù):

  • json.dumps(): 對數(shù)據(jù)進行編碼。
  • json.loads(): 對數(shù)據(jù)進行解碼。

在 json 的編解碼過程中,Python 的原始類型與 json 類型會相互轉(zhuǎn)換,具體的轉(zhuǎn)化對照如下:

Python 編碼為 JSON 類型轉(zhuǎn)換對應(yīng)表:

Python JSON
dict object
list, tuple array
str string
int, float, int- & float-derived Enums number
True true
False false
None null

JSON 解碼為 Python 類型轉(zhuǎn)換對應(yīng)表:

JSON Python
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None

json.dumps 與 json.loads 實例

以下實例演示了 Python 數(shù)據(jù)結(jié)構(gòu)轉(zhuǎn)換為JSON:

實例(Python 3.0+)

#!/usr/bin/python3

import

json

# Python 字典類型轉(zhuǎn)換為 JSON 對象

data
= {
'
no
'
:
1
,
'
name
'
:
'
Runoob
'
,
'
url
'
:
'
http://www.runoob.com
'
}
json_str
=
json
.
dumps
(
data
)

print

(
"
Python 原始數(shù)據(jù):
"
,
repr
(
data
)
)

print

(
"
JSON 對象:
"
,
json_str
)

執(zhí)行以上代碼輸出結(jié)果為:

Python 原始數(shù)據(jù): {'url': 'http://www.runoob.com', 'no': 1, 'name': 'Runoob'}
JSON 對象: {"url": "http://www.runoob.com", "no": 1, "name": "Runoob"}

通過輸出的結(jié)果可以看出,簡單類型通過編碼后跟其原始的repr()輸出結(jié)果非常相似。

接著以上實例,我們可以將一個JSON編碼的字符串轉(zhuǎn)換回一個Python數(shù)據(jù)結(jié)構(gòu):

實例(Python 3.0+)

#!/usr/bin/python3

import

json

# Python 字典類型轉(zhuǎn)換為 JSON 對象

data1
= {
'
no
'
:
1
,
'
name
'
:
'
Runoob
'
,
'
url
'
:
'
http://www.runoob.com
'
}
json_str
=
json
.
dumps
(
data1
)

print

(
"
Python 原始數(shù)據(jù):
"
,
repr
(
data1
)
)

print

(
"
JSON 對象:
"
,
json_str
)

# 將 JSON 對象轉(zhuǎn)換為 Python 字典

data2
=
json
.
loads
(
json_str
)

print

(
"
data2['name']:
"
,
data2
[
'
name
'
]
)

print

(
"
data2['url']:
"
,
data2
[
'
url
'
]
)

執(zhí)行以上代碼輸出結(jié)果為:

Python 原始數(shù)據(jù): {'name': 'Runoob', 'no': 1, 'url': 'http://www.runoob.com'}
JSON 對象: {"name": "Runoob", "no": 1, "url": "http://www.runoob.com"}
data2['name']:  Runoob
data2['url']:  http://www.runoob.com

如果你要處理的是文件而不是字符串,你可以使用 json.dump()json.load() 來編碼和解碼JSON數(shù)據(jù)。例如:

實例(Python 3.0+)

# 寫入 JSON 數(shù)據(jù)

with

open
(
'
data.json
'
,
'
w
'
)

as

f
:
json
.
dump
(
data
,
f
)

# 讀取數(shù)據(jù)

with

open
(
'
data.json
'
,
'
r
'
)

as

f
:
data
=
json
.
load
(
f
)

更多資料請參考:


文章題目:Python3JSON數(shù)據(jù)解析
當前URL:http://m.5511xx.com/article/dpcgsdg.html