日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Python3 JSON处理

發布時間:2025/4/14 javascript 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python3 JSON处理 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

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

Python編碼-->JSON 類型轉換對應表:

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int- & float-derived Enumsnumber
Truetrue
Falsefalse
Nonenull

?

?

?

?

?

?

JSON解碼? -->Python 類型轉換對應表:

JSONPython
objectdict
arraylist
stringstr
number (int)int
number (real)float
trueTrue
falseFalse
nullNone

?

?

?

?

?

?

?

?

#!/usr/bin/python3import json# Python 字典類型轉換為 JSON 對象 data = {'no' : 1,'name' : 'Runoob','url' : 'http://www.runoob.com' }json_str = json.dumps(data) print ("Python 原始數據:", repr(data)) print ("JSON 對象:", json_str)

輸出結果為:

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

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

接著以上實例,我們可以將一個JSON編碼的字符串轉換回一個Python數據結構:

# 將 JSON 對象轉換為 Python 字典 data2 = json.loads(json_str) print ("data2['name']: ", data2['name']) print ("data2['url']: ", data2['url'])

輸出結果為:

Python 原始數據: {'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數據。例如:

寫入 JSON 數據 with open('data.json', 'w') as f:json.dump(data, f)# 讀取數據 with open('data.json', 'r') as f:data = json.load(f)

?

Changed in version 3.6:?All parameters are now?keyword-only.

default(o):

def default(self, o):try:iterable = iter(o)except TypeError:passelse:return list(iterable)# Let the base class default method raise the TypeErrorreturn json.JSONEncoder.default(self, o)

encode(o):

json.JSONEncoder().encode({"foo": ["bar", "baz"]}) '{"foo": ["bar", "baz"]}'

iterencode(o):

for chunk in json.JSONEncoder().iterencode(bigobject):mysocket.write(chunk)

?

轉載于:https://www.cnblogs.com/huangsxj/p/8649494.html

總結

以上是生活随笔為你收集整理的Python3 JSON处理的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。