Python与Json

概述

JSON 是一种轻量级的数据交换格式 (JavaScript Object Notation)

Python对JSON的处理相当简单

主要用到 json模块,四大函数:

处理的如果是程序对象:

  • json.dumps 编码

  • json.loads 解码

处理的如果是文件

  • json.dump 写入文件
  • json.load 读出文件

转化规则

python数据格式与json转化的关系如下

Python 编码为 JSON 类型转换对应表

Python JSON
dict object
list, tuple array
str string
int, float, int- & float-derived Enums number
True true
False false
None null

JSON 解码为 Python 类型转换对应表:

JSON Python
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None

举例

开始前,Python 當中自帶 json 套件,所以我們不必另外安裝,可以直接在程式碼中匯入這個模組。

import json

tips:让数据格式化输出:

json.dumps( source , sort_keys=True, indent=4, separators=(',', ': '))

dumps

用dict来举例,按转化规则变成一个Object

>>> import json
>>> dict = {"liuxunzhuo":{"job":"engineer","gender":"male","experience":{"2020":"AirSpider","2019":"NovelDao"},"wanyueke":{"job":"lawer","gender":"female","experience":"None"}}
... }
>>> dict
{'liuxunzhuo': {'job': 'engineer', 'gender': 'male', 'experience': {'2020': 'AirSpider', '2019': 'NovelDao'}, 'wanyueke': {'job': 'lawer', 'gender': 'female', 'experience': 'None'}}}
>>> json_dict = json.dumps(dict,sort_keys=True, indent=4, separators=(',', ': '))
>>> print(json_dict)
{
    "liuxunzhuo": {
        "experience": {
            "2019": "NovelDao",
            "2020": "AirSpider"
        },
        "gender": "male",
        "job": "engineer",
        "wanyueke": {
            "experience": "None",
            "gender": "female",
            "job": "lawer"
        }
    }
}

loads

接着上面的例子,将json转化为dict

>>> res = json.loads(json_dict)
>>> print(res)
{'liuxunzhuo': {'experience': {'2019': 'NovelDao', '2020': 'AirSpider'}, 'gender': 'male', 'job': 'engineer', 'wanyueke': {'experience': 'None', 'gender': 'female', 'job': 'lawer'}}}
>>>

dump

直接将python数据转化成json格式写入文档

>>> import json
>>> dict = {"liuxunzhuo":{"job":"engineer","gender":"male","experience":{"2020":"AirSpider","2019":"NovelDao"},"wanyueke":{"job":"lawer","gender":"female","experience":"None"}}
... }
>>> file = open("test.txt","w")
>>> json.dump(dict , file,sort_keys=True, indent=4, separators=(',', ': '))
>>> file.close()

结果如下:

load

将json文档读入并转化为python数据

>>> file = open("test.txt","r")
>>> read = json.load(file)
>>> print(read)
{'liuxunzhuo': {'experience': {'2019': 'NovelDao', '2020': 'AirSpider'}, 'gender': 'male', 'job': 'engineer', 'wanyueke': {'experience': 'None', 'gender': 'female', 'job': 'lawer'}}}
>>>

用好这四个函数就能轻松应对大部分问题啦

Default image
LIU
代码是躯体,思想是灵魂

Leave a Reply