Python读写JSON格式的文本文件
- 1. 使用JSON模块读写
- 1.1 整体写入
- 1.2 按行写入
- 1.3 整体读取
- 1.4 按行读取
- 2. 使用Pandas库读写
- 2.1 整体读取
- 2.2 整体写入
JSON
是一种轻量级的数据交换格式,易于人们编写和机器解析与生成。JSON
虽然采用了完全独立与语言的文本格式,但也使用了一些C
语言的特性,这些特性是JSON
称为一种理想的数据交换语言。在Python
中读写JSON
格式的文本通常使用两种方法,使用 JSON
模块读写和使用 Pandas
库读写。
1. 使用JSON模块读写
Python
内置了处理JSON
的json
模块,可以直接处理字符串,整型,浮点型,列表,元组,字典等类型的数据。将Python
原始数据类型转为JSON
类型的过程称为序列化,序列化前后对应关系图如下。
Python类型 | JSON类型 |
dict | object |
list, tuple | array |
str | string |
int, long, float | number |
True | true |
False | false |
None | null |
将JSON
类型转换为Python
类型的过程称为反序列化(从JSON
文件中读取数据),反序列化前后关系对应表如下。
JSON类型 | Python类型 |
object | dict |
array | list |
string | str |
number(int) | int, long |
number(real) | float |
true | True |
false | False |
null | None |
1.1 整体写入
import json
obj = [[1,2,3], 123, 123.000, 'ab', {'name': 'Jerry', 'age': 18}]
with open('test.json', 'w') as fp:
json.dump(obj, fp)
1.2 按行写入
import json
obj = [[1,2,3], 123, 123.000, 'ab', {'name': 'Jerry', 'age': 18}]
for item in obj:
with open('test.json', 'a+', encoding='utf-8') as fp:
line = json.dumps(item, ensure_ascii=False)
fp.write(line + '\n')
1.3 整体读取
import json
obj = json.load(open('test.json'))
print(obj)
1.4 按行读取
import json
obj = []
with open('test.json', 'r', encoding="utf-8") as fp:
# 读取所有行,数据格式为字符串
for row in fp.readlines():
print(type(row))
# 将字符串转化为原本格式
row = json.loads(row)
print(type(row))
print('-'*10)
obj.append(row)
print(obj)
<class 'str'>
<class 'list'>
----------
<class 'str'>
<class 'int'>
----------
<class 'str'>
<class 'float'>
----------
<class 'str'>
<class 'str'>
----------
<class 'str'>
<class 'dict'>
----------
[[1, 2, 3], 123, 123.0, 'ab', {'name': 'Jerry', 'age': 18}]
2. 使用Pandas库读写
2.1 整体读取
test.json
文件内容
import pandas as pd
df = pd.read_json('test.json')
df
2.2 整体写入
import pandas as pd
df = pd.DataFrame({'name': ['Tom', 'Jerry'], 'age': [10, 11]})
df
with open('test.json', 'w')as fp:
fp.write(df.to_json(force_ascii=False))