當(dāng)前位置:
首頁(yè) >
前端技术
> javascript
>内容正文
javascript
Python高级编程——JSON
生活随笔
收集整理的這篇文章主要介紹了
Python高级编程——JSON
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Python3 JSON 數(shù)據(jù)解析
JSON (JavaScript Object Notation) 是一種輕量級(jí)的數(shù)據(jù)交換格式。它基于ECMAScript的一個(gè)子集。
Python3 中可以使用 json 模塊來(lái)對(duì) JSON 數(shù)據(jù)進(jìn)行編解碼,它包含了兩個(gè)函數(shù):
- json.dumps(): 對(duì)數(shù)據(jù)進(jìn)行編碼。
- json.loads(): 對(duì)數(shù)據(jù)進(jìn)行解碼。
在json的編解碼過(guò)程中,python 的原始類型與json類型會(huì)相互轉(zhuǎn)換
Python 編碼為 JSON 類型轉(zhuǎn)換對(duì)應(yīng)表:
| dict | object |
| list, tuple | array |
| str | string |
| int, float, int- & float-derived Enums | number |
| True | true |
| False | false |
| None | null |
JSON 解碼為 Python 類型
只需把上表反過(guò)來(lái),不贅述了。注意下表不同之處
| number (int) | int |
| number (real) | float |
實(shí)例
Python 數(shù)據(jù)結(jié)構(gòu)轉(zhuǎn)換為JSON
import json# Python 字典類型轉(zhuǎn)換為 JSON 對(duì)象 data = {'no' : 1,'name' : 'SB','url' : 'http://www.SB.com' }json_str = json.dumps(data) print ("Python 原始數(shù)據(jù):", repr(data)) print ("JSON 對(duì)象:", json_str)結(jié)果為:
Python 原始數(shù)據(jù): {'url': 'http://www.SB.com', 'no': 1, 'name': 'SB'} JSON 對(duì)象: {"url": "http://www.SB.com", "no": 1, "name": "SB"}JSON編碼的字符串轉(zhuǎn)換回一個(gè)Python數(shù)據(jù)結(jié)構(gòu):
import json data1 = {'no' : 1,'name' : 'SB','url' : 'http://www.SB.com' }json_str = json.dumps(data1) print ("Python 原始數(shù)據(jù):", repr(data1)) print ("JSON 對(duì)象:", json_str)# 將 JSON 對(duì)象轉(zhuǎn)換為 Python 字典 data2 = json.loads(json_str) print ("data2['name']: ", data2['name']) print ("data2['url']: ", data2['url'])結(jié)果為:
Python 原始數(shù)據(jù): {'name': 'SB', 'no': 1, 'url': 'http://www.SB.com'} JSON 對(duì)象: {"name": "SB", "no": 1, "url": "http://www.SB.com"} data2['name']: SB data2['url']: http://www.SB.com如果你要處理的是文件而不是字符串,你可以使用 json.dump() 和 json.load() 來(lái)編碼和解碼JSON數(shù)據(jù)。
# 寫(xiě)入 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)總結(jié)
以上是生活随笔為你收集整理的Python高级编程——JSON的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 如何选择一个合适高效率的光纤熔接机--T
- 下一篇: JavaScript十进制转换为二进制