1.dump和load/dumps和loads区别
dump和load是对于json格式的写入和读取
dumps和loads只是类型转换
可填参数
参数 |
说明 |
skipkey |
默认为False,当dict对象里的数据不是Python的基本数据类型(str,unicode,int,long,float,bool,None)时,当skipkey为False,就会报错,如果skipkey为True,则可以跳过这类key; |
indent |
如果填0或者不填,则按照一行进行打印,否则按照indent的数值显示前面的空格(正整数形式) |
separators |
分隔符,默认为“(',','😂”,它表示key之间用“,”隔开,key和value之间用“:”隔开 |
encoding |
编码格式,默认值是UTF-8 |
sort_keys |
对key、value进行排序,默认值是False,即不排序 |
ensure_ascii |
默认为True,如果dict对象里含有none-ASCII的字符,则显示\uXX的格式,如果为False,则能正常显示出来 |
2.读写操作
dump
import json
data = {'str3':'xyz','str2' :'efgh','str1':'abcd'}
with open(' data. txt', '', encoding='utf-8') as f:
# f.write (json.dumps (data)) 效果一样
json.dump(data, f)
load
with open(' data. txt', 'r') as f:
# d2 = json.loads (f.read()) 效果一样
d2 = json.load(f)
3.类型转换
dumps
dumps函数是对数据进行编码,形成json格式的数据
data_dict = {"key2": "value2", "key1": "value1"}
# 有序转换json字符串
json1 = json.dumps(data_dict, sort_keys=True)
print(json1) # {"key1": "value1", "key2": "value2"}
# 默认无序
json2 = json.dumps(data_dict)
print(json2) # {"key2": "value2", "key1": "value1"}
loads
loads函数则是将json格式的数据解码,转换为Python字典
import json
data_str = '{"key1": "value1", "key2": "value2", "key3": "value3"}'
# 默认无序
data_dict = json.loads(data_str)
print(data_dict)
4.文件操作(参考)
普通文本文件
json文件
{}
# 读取json文件
def select_user():
with open(settings.USER_JSON_PATH, 'r', encoding='utf-8') as f:
user_dict = json.load(f)
return user_dict
# 写入
def create_user(user,pwd):
user_dict = select_user()
user_dict[user] = pwd
with open(settings.USER_JSON_PATH, 'w', encoding='utf-8') as f:
json.dump(user_dict, f, ensure_ascii=False)
二进制文件
def select():
with open(settings.USER_JSON_PATH, 'rb') as f:
user_dict = json.load(f)
return user_dict
def create(data):
with open(settings.USER_JSON_PATH, 'wb') as f:
'''
文件使用wb写入的,所有需要使用bytes类型写入
'''
a = json.dumps(data) # a现在是str类型
f.write(a.encode('utf-8')) # 需要进行转码,bytes类型
if __name__ == '__main__':
data = select()
print(data)
data['absssc'] = 122
create(data)