Python3快速入門(八)——Python3 JSON

Python3快速入門(八)——Python3 JSON

一、JSON簡介

JSON (JavaScript Object Notation) 是一種輕量級的數據交換格式,是基於ECMAScript的一個子集。json

二、json模塊簡介

Python3 中能夠使用 json 模塊來對 JSON 數據進行編解碼,包含兩個函數:
json.dumps(): 對數據進行編碼。
json.loads(): 對數據進行解碼。
在json的編解碼過程當中,Python 的數據類型與json類型會相互轉換。
json.dump():將數據保存爲JSON文件
json.load():從JSON文件讀取數據
Python數據類型編碼爲JSON數據類型轉換表:
dict object
list,tuple array
str string
Int,float,enum number
True true
False false
None null
JSON解碼爲Python數據類型轉換表:
object dict
array list
string str
number(int) int
number(real) float
true True
false False
null Noneide

三、JSON實例

# -*- coding:utf-8 -*-
import json

data = {
    "id":"123456",
    "name":"Bauer",
    "age":30
}

jsonFile = "data.json"

if __name__ == '__main__':
    # 將字典數據轉換爲JSON對象
    print("raw data: ", data)
    jsonObject = json.dumps(data)
    print("json data: ", jsonObject)
    # 將JSON對象轉換爲字典類型數據
    rowData = json.loads(jsonObject)
    print("id: ", rowData["id"])
    print("name: ", rowData["name"])
    print("age: ", rowData["age"])
    # 將JSON對象保存爲JSON文件
    with open(jsonFile, 'w') as file:
        json.dump(jsonObject, file)
    # 將JSON文件讀取內容
    with open(jsonFile, 'r') as file:
        data = json.load(file)
        print(data)

# output:
# raw data:  {'id': '123456', 'name': 'Bauer', 'age': 30}
# json data:  {"id": "123456", "name": "Bauer", "age": 30}
# id:  123456
# name:  Bauer
# age:  30
# {"id": "123456", "name": "Bauer", "age": 30}
相關文章
相關標籤/搜索