读写json文件
读取
直接举个例子:
data = []
with open('./data/dev_data.json', 'r', encoding='utf-8') as f:
for line in f.readlines(): # 字符串
line = json.loads(line.strip()) # 将字符串转为dict
data.append(line) # data中的每个元素是dict
从json文件中依次读取出每一行,读取出来的是字符串形式。然后用json.loads()方法将字符串转为dict。最后放在data列表里。
写入
例子:
# ls = [1, 2, 3]
ls1 = [(1, 't'), (2, 'h'), (3, 'z')]
ls2 = [(1, 't'), (2, 'h'), (3, 'z')]
# 写入json文件
with open('data/a.json', 'w') as f:
str1 = json.dumps(ls1) # list转字符串
str2 = json.dumps(ls2)
# f.write(str1)
# f.write('\n')
f.writelines(str1+'\n') # 将字符串写入文件并换行
f.writelines(str2+'\n')
被写入的文件格式如下:
[[1, "t"], [2, "h"], [3, "z"]]
[[1, "t"], [2, "h"], [3, "z"]]
注意事项
将array数组存入json文件:array对象是不能直接转化为json对象的,所以需要先转为list。
(1)将整个array数组一次性存入json文件:
data_path = 'a.json'
z = np.array([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13, 14, 15, 16]]) # 4, 4
ls = z.tolist()
s = json.dumps(ls)
print(type(s))
print(s)
with open(data_path, 'w') as fw:
a_ls = json.dumps(z.tolist())
fw.writelines(a_ls+'\n')
运行结果:
<class 'str'>
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
整个array数组先被转为list,然后被存入json文件。
(2)将array数组按行存入json文件:
data_path = 'a.json'
z = np.array([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13, 14, 15, 16]]) # 4, 4
# z1 = z[0] z的第一行
# ls = z1.tolist()
with open(data_path, 'w') as fw:
len = z.shape[0]
for i in range(len):
zi = z[i].reshape(-1) # array shape:[4]
zi_list = zi.tolist()
zi_str = json.dumps(zi_list) # str
fw.writelines(zi_str+'\n')
json文件中内容:
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]
[13, 14, 15, 16]