搜尋
首頁後端開發Python教學Python對JSON的解析詳解

Python對JSON的解析詳解

Sep 19, 2017 am 11:13 AM
javascriptjsonpython

JSON 函數

使用 JSON 函數需要匯入 json 函式庫:import json。

函數 描述

json.dumps  將Python 物件編碼成JSON 字串

json.loads  將已編碼的JSON 字串解碼為Python 物件

json.dumps

語法

json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None , encoding="utf-8", default=None, sort_keys=False, **kw)

實例

以下實例將陣列編碼為JSON 格式資料:

#!/usr/bin/python
import json
data = {'number': 6, 'name': 'Pythontab'}
jsonData = json.dumps(data)
print jsonData

以上程式碼執行結果為:

{"number": 6, "name": "Pythontab"}

注意: 大家可能發現,執行上述轉換以後,資料並沒有發生變化,這裡要說一下: 在json中雙引號才是標註的字串分割符號,單引號不標準。

使用參數讓JSON 資料排序並格式化輸出:

#!/usr/bin/python
import json
data = {'number': 6, 'name': 'Pythontab'}
jsonData = json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
print jsonData

輸出結果

{
    "name": "Pythontab",
    "number": 6
}

python 原始類型轉換到json 類型的對照表:

list, tuplearray#str, unicodestringint, long, floatnumberTruetrue
Python JSON
#dict object
##False


#false

None

null

json.loads

json.loads 用於解碼JSON 資料。此函數傳回 Python 欄位的資料類型。

語法json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[,kw]]]] **kw]]]] ]])實例以下實例展示了Python 如何解碼JSON 物件:以上程式碼執行結果為:json 類型轉換到python 的型別對照表:JSON##Pythonobjectdict#arrayliststring unicode
#!/usr/bin/python
import json
jsonData = '{"number": 6, "name": "Pythontab"}'
str = json.loads(jsonData)
print str
{u'number': 6, u'name': u'Pythontab'}


number (int)

int, long

number (real)

float

true

True

false

#False

################## #######null######None##################使用第三方函式庫:Demjson######Demjson 是python 的第三方模組庫,可用於編碼和解碼JSON 數據,包含了JSONLint 的格式化及校驗功能。 ######Github 位址:https://github.com/dmeranda/demjson######環境配置######在使用Demjson 編碼或解碼JSON 資料前,我們需要先安裝Demjson 模組。 ######方法1:原始碼安裝######$ tar -xvzf demjson-2.2.4.tar.gz######$ cd demjson-2.2.2.4######$ python setup.py install######方法2:直接使用pip安裝######pip install Demjson######JSON 函數######函數 描述#######encode將Python 物件編碼成JSON 字串######decode  可以使用demjson.decode() 函數解碼JSON 資料。此函數傳回 Python 欄位的資料類型。 ######encode語法######demjson.encode(self, obj, nest_level=0)#########demjson.encode(self, obj, nest_level=0)######decode語法######demjson.decode(self, txt)## ####使用都很簡單,我就不在這裡舉例~~###

以上是Python對JSON的解析詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

在Numpy陣列上可以執行哪些常見操作?在Numpy陣列上可以執行哪些常見操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的數據分析中如何使用陣列?Python的數據分析中如何使用陣列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

列表的內存足跡與python數組的內存足跡相比如何?列表的內存足跡與python數組的內存足跡相比如何?May 02, 2025 am 12:08 AM

列表sandnumpyArraysInpythonHavedIfferentMemoryfootprints:listSaremoreFlexibleButlessMemory-效率,而alenumpyArraySareSareOptimizedFornumericalData.1)listsStorReereReereReereReereFerenceStoObjects,with withOverHeadeBheadaroundAroundaround64byty64-bitsysysysysysysysysyssyssyssyssysssyssys2)

部署可執行的Python腳本時,如何處理特定環境的配置?部署可執行的Python腳本時,如何處理特定環境的配置?May 02, 2025 am 12:07 AM

toensurepythonscriptsbehavecorrectlyacrycrosdevelvermations,分期和生產,USETHESTERTATE:1)Environment varriablesForsimplesettings,2)configurationfilesfilesForcomPlexSetups,3)dynamiCofforComplexSetups,dynamiqualloadingForaptaptibality.eachmethodoffersuniquebeneiquebeneqeniquebenefitsandrefitsandrequiresandrequiresandrequiresca

您如何切成python陣列?您如何切成python陣列?May 01, 2025 am 12:18 AM

Python列表切片的基本語法是list[start:stop:step]。 1.start是包含的第一個元素索引,2.stop是排除的第一個元素索引,3.step決定元素之間的步長。切片不僅用於提取數據,還可以修改和反轉列表。

在什麼情況下,列表的表現比數組表現更好?在什麼情況下,列表的表現比數組表現更好?May 01, 2025 am 12:06 AM

ListSoutPerformarRaysin:1)DynamicsizicsizingandFrequentInsertions/刪除,2)儲存的二聚體和3)MemoryFeliceFiceForceforseforsparsedata,butmayhaveslightperformancecostsinclentoperations。

如何將Python數組轉換為Python列表?如何將Python數組轉換為Python列表?May 01, 2025 am 12:05 AM

toConvertapythonarraytoalist,usEthelist()constructororageneratorexpression.1)intimpthearraymoduleandcreateanArray.2)USELIST(ARR)或[XFORXINARR] to ConconverTittoalist,請考慮performorefformanceandmemoryfformanceandmemoryfformienceforlargedAtasetset。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。