Python JSON常用編解碼方法代碼實(shí)例
概念
JSON(JavaScript Object Notation) 是一種輕量級(jí)的數(shù)據(jù)交換格式,易于人閱讀和編寫。在日常的工作中,應(yīng)用范圍極其廣泛。這里就介紹python下它的兩種編解碼方法:
使用json函數(shù)
使用 JSON 函數(shù)需要導(dǎo)入 json 庫:import json。函數(shù)含義:
源碼解析:
# coding= utf-8#!/usr/bin/pythonimport jsonimport sys data = {'username':'測(cè)試','age':16}#jsondata = json.dumps(data,ensure_ascii=False)jsondata = json.dumps(data)print('data convert to json')print type(json)text = json.loads(jsondata)print('json convert to data')print text['username']print text['age']
使用第三方庫:Demjson
Demjson 是 python 的第三方模塊庫,可用于編碼和解碼 JSON 數(shù)據(jù),包含了 JSONLint 的格式化及校驗(yàn)功能。
函數(shù)定義:
源碼解析:
#!/usr/bin/pythonimport demjsondata = [ { ’a’ : 1, ’b’ : 2, ’c’ : 3, ’d’ : 4, ’e’ : 5 } ] json = demjson.encode(data)print jsontext = demjson.decode(json)print text
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python如何批量生成和調(diào)用變量2. Python調(diào)用接口合并Excel表代碼實(shí)例3. python全棧開發(fā)語法總結(jié)4. 如何在Python項(xiàng)目中引入日志5. ASP.Net Core對(duì)USB攝像頭進(jìn)行截圖6. ajax動(dòng)態(tài)加載json數(shù)據(jù)并詳細(xì)解析7. python b站視頻下載的五種版本8. 通過CSS數(shù)學(xué)函數(shù)實(shí)現(xiàn)動(dòng)畫特效9. ASP.Net Core(C#)創(chuàng)建Web站點(diǎn)的實(shí)現(xiàn)10. Python快速將ppt制作成配音視頻課件的操作方法
