标签:使用 pen 目录 字符串类 int with open coding 浮点 lan
json(JavaScript Object Notation)是一种轻量级的数据交换格式。简单和清晰的层次结构使得json成为理想的数据交换语言。易于阅读和编写,同时也易于机器解析和生成,并有效的提升网络传输效率。
json支持的数据格式:
多个数据之间使用逗号隔开
注意:json本质就是一个字符串。
json数据在线格式化网站:https://www.json.cn/
import json
emp = [
{
"ename":"Jack",
"age":18,
"addr":"Kunming"
},
{
"ename": "Lucy",
"age": 18,
"addr": "Qujing"
}
]
json_str = json.dumps(emp)
print(type(json_str))
print(json_str)
输出结果:
<class ‘str‘>
[{"ename": "Jack", "age": 18, "addr": "Kunming"}, {"ename": "Lucy", "age": 18, "addr": "Qujing"}]
从结果可以看出,json确实是一个字符串。
如果我们想要把上述得到的json写入到文件中,那么可以这么写
import json
emp = [
{
"ename":"Jack",
"age":18,
"addr":"Kunming"
},
{
"ename": "Lucy",
"age": 18,
"addr": "Qujing"
}
]
json_str = json.dumps(emp)
with open("emp.json","w") as f:
f.write(json_str)
但是在json中提供了一个更加方便的方法dump
,可以直接将数据写入到文件中,代码如下:
import json
emp = [
{
"ename":"Jack",
"age":18,
"addr":"Kunming"
},
{
"ename": "Lucy",
"age": 18,
"addr": "Qujing"
}
]
with open("emp.json","w") as f:
json.dump(emp,f)
如果是转换的内容中包含了中文,json在dump的时候,只能存放ascii
字符,因此会对中文进行转义,这时候,我们可以使用ensure_ascii=False
关闭这个特性。
# Author:Logan
import json
emp = [
{
"ename":"关羽",
"age":18,
"addr":"Kunming"
},
{
"ename": "张飞",
"age": 18,
"addr": "Qujing"
}
]
with open("emp.json", "w", encoding="utf-8") as f:
json.dump(emp, f, ensure_ascii=False)
转换后的结果如下:
import json
json_str = ‘[{"ename": "关羽", "age": 18, "addr": "Kunming"}, {"ename": "张飞", "age": 18, "addr": "Qujing"}]‘
emp = json.loads(json_str)
print(type(emp))
for e in emp:
print(e)
输出结果:
<class ‘list‘>
{‘ename‘: ‘关羽‘, ‘age‘: 18, ‘addr‘: ‘Kunming‘}
{‘ename‘: ‘张飞‘, ‘age‘: 18, ‘addr‘: ‘Qujing‘}
import json
with open("emp.json", "r", encoding="utf-8") as f:
emp = json.load(f)
print(type(emp))
for e in emp:
print(e)
标签:使用 pen 目录 字符串类 int with open coding 浮点 lan
原文地址:https://www.cnblogs.com/OliverQin/p/12630139.html