Python JSON

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

  • JSON独立于语言
  • JSON具有自我描述性,更易理解
  • JSON比XML更小、更快、更易解析

Python 中可以使用 json 模块来对 JSON 数据进行编解码。

官方文档:https://docs.python.org/3.8/library/json.html

dumps和loads

它包含了两个函数:

  • json.dumps(): 对数据进行编码。
  • json.loads(): 对数据进行解码。

 

使用json 字符串生成python对象(load)
使用python对象格式化成json对象(dump)

j son 的编解码过程中,Python 的原始类型与 json 类型会相互转换,具体的转化对照如下:

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

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

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

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

json.dumps 与 json.loads 实例

 Python 数据结构转换为JSON:

import json

# Python 字典类型转换为 JSON 对象
data = {
    'no': 1,
    'name': 'test',
    'url': 'http://www.test.com'
}

json_str = json.dumps(data)
print("Python 原始数据:", repr(data))
print("JSON 对象:", json_str)

执行以上代码输出结果为:

Python 原始数据: {'no': 1, 'name': 'test', 'url': 'http://www.test.com'}
JSON 对象: {"no": 1, "name": "test", "url": "http://www.test.com"}

通过输出的结果可以看出,简单类型通过编码后跟其原始的repr()输出结果非常相似。

接着以上实例,我们可以将一个JSON编码的字符串转换回一个Python数据结构:

import json

# Python 字典类型转换为 JSON 对象
data1 = {
    'no': 1,
    'name': 'test',
    'url': 'http://www.test.com'
}

json_str = json.dumps(data1)
print("Python 原始数据:", repr(data1))
print("JSON 对象:", json_str)

# 将 JSON 对象转换为 Python 字典
data2 = json.loads(json_str)
print("data2['name']: ", data2['name'])
print("data2['url']: ", data2['url'])

执行以上代码输出结果为:

Python 原始数据: {'no': 1, 'name': 'test', 'url': 'http://www.test.com'}
JSON 对象: {"no": 1, "name": "test", "url": "http://www.test.com"}
data2['name']:  test
data2['url']:  http://www.test.com

如果你要处理的是文件而不是字符串,你可以使用 json.dump()json.load() 来编码和解码JSON数据。例如:

# 写入 JSON 数据
with open('data.json', 'w') as f:
    json.dump(data, f)
 
# 读取数据
with open('data.json', 'r') as f:
    data = json.load(f)

 

posted @ 2021-07-09 16:40  王陸  阅读(200)  评论(1编辑  收藏  举报