json.dumps将一个Python数据结构转换为JSON
import json
data = {
'name' : 'myname',
'age' : 100,
}
json_str = json.dumps(data)
方法 | 作用 |
---|---|
json.dumps() | 将python对象编码成Json字符串 |
json.loads() | 将Json字符串解码成python对象 |
json.dump() | 将python中的对象转化成json储存到文件中 |
json.load() | 将文件中的json的格式转化成python对象提取 |
json.dump()和json.dumps()的区别
json参数
json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)
import json
x = {'name':'你猜','age':19,'city':'四川'}
#用dumps将python编码成json字符串
y = json.dumps(x)
print(y)
i = json.dumps(x,separators=(',',':'))
print(i)
# 输出结果
{"name": "\u4f60\u731c", "age": 19, "city": "\u56db\u5ddd"}
{"name":"\u4f60\u731c","age":19,"city":"\u56db\u5ddd"}
json.dumps()用于将python对象转换为json字符串,返回转换后的json字符串
import json
#将python对象转换为json字符串
persons = [
{
'username': "zhaoji",
"age": "18",
"country": "China"
},
{
"username": "cyj",
"age": "18",
"country": "China"
}
]
#调用dumps方法转换python对象
json_str = json.dumps(persons)
#打印转换后的json字符串的数据类型
print(type(json_str))
#打印转换后的json字符串
print(json_str)
输出结果为
[{“username”: “zhaoji”, “age”: “18”, “country”: “China”}, {“username”: “cyj”, “age”: “18”, “country”: “China”}]Process finished with exit code 0
json.dump()用于将python对象转换为字符串并且写入文件
import json
#将python对象转换为json字符串
persons = [
{
'username': "zhaoji",
"age": "18",
"country": "China"
},
{
"username": "cyj",
"age": "18",
"country": "China"
}
]
with open("./data/j1.json", "w") as fp:
json.dump(persons, fp)
fp.close()
写入文件为
[{“username”: “zhaoji”, “age”: “18”, “country”: “China”}, {“username”: “cyj”, “age”: “18”, “country”: “China”}]
到此这篇关于Python中json.dumps()函数的使用解析的文章就介绍到这了,更多相关Python json.dumps() 内容请搜索python博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持python博客!
Powered By python教程网 鲁ICP备18013710号
python博客 - 小白学python最友好的网站!