avatar

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 套件,所以我們不必另外安裝,可以直接在程式碼中匯入這個模組。

1
import json

tips:让数据格式化输出:

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

dumps

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
>>> 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

1
2
3
4
>>> 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格式写入文档

1
2
3
4
5
6
>>> 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数据

1
2
3
4
5
>>> 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'}}}
>>>

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

Author: 1900
Link: https://www.liuxunzhuo.tech/json.html
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
    微信
  • 支付寶
    支付寶

Comment