目录
1. import json
- 1. import json
- 2. dict转str
- 3. json格式的str转dict
- 4. 保存数据到文件,再从文件中读取数据
import json
2. dict转str
map = {"键1":"值1", "键2":"值2"}
str1 = json.dumps(map)
print(str1) # {"\u952e1": "\u503c1", "\u952e2": "\u503c2"}
str2 = json.dumps(map, ensure_ascii = False)
print(str2) # {"键1": "值1", "键2": "值2"}
默认是使用ascii编码,这样中文无法阅读,所有使用ensure_ascii = False关闭ascii
3. json格式的str转dictjson_str='{"键1": "值1", "键2": "值2"}'
map = json.loads(json_str)
print(type(map)) #
print(map) # {'键1': '值1', '键2': '值2'}
4. 保存数据到文件,再从文件中读取数据
文件不一定是.json
类型的
import os
import json
if __name__ == '__main__':
names = ['zhang_san', 'li_si', 'wang_wu']
file_path = os.getcwd() + r'/test.txt'
with open(file_path, 'w', encoding='utf-8') as f:
# 将数据导入到文件中
json.dump(names, f)
with open(file_path, 'r', encoding='utf-8') as f:
# 从文件中加载数据
read_content = json.load(f)
print(read_content) # ['zhang_san', 'li_si', 'wang_wu']
test.txt文件内容如下:
["zhang_san", "li_si", "wang_wu"]