在python中将json转成字符串的方法:首先打印出数据的类型;然后输入“str = json.dumps(data,indent=2)”命令将json转换为字符串,最后使用print语句打印出字符串即可。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import json
data = [{
"name" : "Tom" ,
"gender" : "male"
}, {
"name" : "杰克" ,
"gender" : "男"
}]
#将json格式转为字符串
print (type(data))
str = json.dumps(data, indent=2) #indent=2按照缩进格式
print (type(str))
print (str)
#保存到json格式文件
with open( 'data.json' , 'w' , encoding= 'utf-8' ) as file:
file.write(json.dumps(data, indent=2, ensure_ascii=False)) #ensure_ascii=False可以消除json包含中文的乱码问题
|
运行结果:
没有添加ensure_ascii=False将导致乱码.
1 2 3 4 5 6 7 8 9 10 11 12 | < class 'list' >
< class 'str' >
[
{
"name" : "Tom" ,
"gender" : "male"
},
{
"name" : "\u6770\u514b" ,
"gender" : "\u7537"
}
]
|
data.json文件内容:
添加ensure_ascii=False
1 2 3 4 5 6 7 8 9 10 | [
{
"name" : "Tom" ,
"gender" : "male"
},
{
"name" : "杰克" ,
"gender" : "男"
}
]
|
推荐课程:python基础语法全讲解视频(马哥教育2014版)