Python——JSON模块

JSON 模块


什么是JSON模块?

如果我们要在不同的编程语言之间传递对象,就必须把对象序列化为标准格式,比如XML,但更好的方法是序列化为JSON,因为JSON表示出来就是一个字符串,可以被所有语言读取,也可以方便地存储到磁盘或者通过网络传输。JSON不仅是标准格式,并且比XML更快,而且可以直接在Web页面中读取,非常方便。JSON表示的对象就是标准的JavaScript语言的对象。

如果我们要在不同的编程语言之间传递对象,就必须把对象序列化为标准格式,比如XML,但更好的方法是序列化为JSON,因为JSON表示出来就是一个字符串,可以被所有语言读取,也可以方便地存储到磁盘或者通过网络传输。JSON不仅是标准格式,并且比XML更快,而且可以直接在Web页面中读取,非常方便。

JSON表示的对象就是标准的JavaScript语言的对象

JSON 名称、值对

1
"name" : "菜鸟教程"

JSON 值

Json值可以是:

  • 数字(整数或浮点数) e.g. {“age”:30}
  • 字符串(双引号中)
  • 逻辑值(bool)
  • 数组(中括号中)
  • 对象(在大括号中) e.g. {“name”:”ooc”,”url”:”makeupstories.github.io”}
  • null

JSON格式的语法规范

JSON模块提供了四个方法:dumps, dump, loads, load

(不带s 封装write 和 read)

ase

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import json

# file: a.json
{
"users": [{
"name": "ooc",
"age": 23
},
{
"name": "james",
"age": 27
}
]
}


# 反序列化 # file: json模块.py
with open('a.json','rt',encoding = 'utf-8') as f:
res = json.loads(f.read())
print(type(res))
# <class 'dict'>
with open('a.json',encoding='utf-8') as f:
print(json,load(f)) # 不带s 封装 write 和 read功能

# {'users': [{'name': 'ooc', 'age': 23}, {'name': 'james', 'age': 27}]}

json_info = '''{
"users": [{
"name": "ooc",
"age": 23
},
{
"name": "james",
"age": 27
}
]
}'''

res = json.loads(json_info)
print(res)
# {'users': [{'name': 'ooc', 'age': 23}, {'name': 'james', 'age': 27}]}

with open('b.json','wt',encoding='utf-8') as f:
f.wrtie(json.dumps(json_info))

with open('b.json','wt',encoding='utf-8') as f:
json.dump(json_info,f) # 不带s 封装 write 和 read功能