Python3 Quick Start (eight) - Python3 JSON

Python3 Quick Start (eight) - Python3 JSON

1, JSON Introduction

JSON (JavaScript Object Notation) is a lightweight data-interchange format, based on a subset of ECMAScript.

2, json module Introduction

Python3 json module can be used to encode and decode data to JSON, contains two functions:
json.dumps (): encode the data.
json.loads (): decodes the data.
Encoding and decoding of the json, Python json type data types will be converted to each other.
json.dump (): Save the data file as JSON
json.load (): read data from a file JSON
Python data type is encoded as JSON data type conversion table:
dict Object
List, Array tuple
STR String
Int, a float, enum Number
True to true
False to false
None null
the JSON decoded Python data type conversion table:
Object dict
Array List
String STR
Number (int) int
Number (Real) a float
to true True
to false False
null None

3, JSON examples

# -*- 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}

Guess you like

Origin blog.51cto.com/9291927/2416026