将Python对象转化为json字符串
1、将Python对象转化为json字符串
import json
person=[
{
'username':'中国',
'age':'18',
'country':'china'
},
{
'username':'山东',
'age':'20',
'country':'china'
}
]
json_str=json.dumps(person)
print(type(json_str))
print(json_str)
运行结果
<class 'str'>
[{"username": "zhiliao", "age": "18", "country": "china"}, {"username": "hello", "age": "20", "country": "china"}]
将Python对象转化为json字符串,并保存至本地文件person
import json
#将Python对象转化为json字符串
person=[
{
'username':'zhiliao',
'age':'18',
'country':'china'
},
{
'username':'hello',
'age':'20',
'country':'china'
}
]
json_str=json.dumps(person)
with open("person.json","w")as f:
f.write(json_str)
import json
#将Python对象转化为json字符串
person=[
{
'username':'zhiliao',
'age':'18',
'country':'china'
},
{
'username':'hello',
'age':'20',
'country':'china'
}
]
with open("person.json","w",encoding="utf-8")as f:
json.dump(person,f,ensure_ascii=False)