1 方法介绍
json.loads():解析一个有效的JSON字符串并将其转换为Python字典
json.load():从一个文件读取JSON类型的数据,然后转转换成Python字典
json.dumps(dict, indent):将Python对象转换成json字符串
json.dump(dict, file_pointer):将Python对象写入json文件
2.代码示例
适用文件类型(每一行都是map):
{"name":"小黑","age":23,"hobby":"run"}
{"name":"阿黄","age":24,"hobby":"minton"}
{"name":"小轩","age":24,"hobby":"eat"}
import json
import random
name = 'train_medical.json'
def read_json(file_name):
file = open(file_name,'r',encoding = 'utf-8')
maps = []
for line in file:
maps.append(json.loads(line))
return maps
def write_json(file_name,maps):
with open(file_name,'w',encoding = 'utf-8') as f:
for map_ in maps:
f.write(json.dumps(map_,ensure_ascii = False)+'\n')
data = read_json(name)
def split_data(prop,data):
random.shuffle(data)
index = int(prop * len(data))
return data[:index],data[index:]
train_data,test_data = split_data(0.95,data)
参考: