365Tools
发布时间:2024-03-13 14:30:01
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,遵循欧洲计算机协会制定的 JavaScript 规范(简称 ECMAScript)。JSON 易于人阅读和编写,同时也易于机器解析和生成,能够有效的提升网信息的传输效率,因此它常被作为网络、程序之间传递信息的标准语言,比如客户端与服务器之间信息交互就是以 JSON 格式传递的。
# coding:utf8
import json
#JOSN字符串
website_info='{"name" : "c语言中文网","PV" : "50万","UV" : "20万","create_time" : "2010年"}'
py_dict=json.loads(website_info)
print("python字典数据格式:%s;数据类型:%s"% (py_dict,type(py_dict)))
输出结果:
python字典数据格式:{'name': 'c语言中文网', 'PV': '50万', 'UV': '20万', 'create_time': '2010年'};数据类型:
json.dump(object,f,inden=0,ensure_ascii=False)参数说明如下:
import json
ditc_info={"name" : "c语言中文网","PV" : "50万","UV" : "20万","create_time" : "2010年"}
with open("web.josn","a") as f:
json.dump(ditc_info,f,ensure_ascii=False)
打开 web.json 文件,其内容如下所示:
{
"name": "c语言中文网",
"PV": "50万",
"UV": "20万",
"create_time": "2010年"
}
您也可以将 Python 列表转换成 JSON 字符串,并保存至 json 文件中,如下所示:
import json
item_list = []
item = {'website': '365工具网', 'url': "www.365tools.cn"}
for k,v in item.items():
item_list.append(v)
with open('info_web.json', 'a') as f:
json.dump(item_list, f, ensure_ascii=False)
打开 info_web.json 文件,其内容如下:
["365工具网", "www.365tools.cn"]
import json
site = {'name':'c语言中文网',"url":"www.365tools.cn"}
filename = 'website.json'
with open (filename,'w') as f:
json.dump(site,f,ensure_ascii=False)
with open (filename,'r') as f:
print(json.load(f))
输出结果如下:
{'name': 'c语言中文网', 'url': 'www.365tools.cn'}
import json
#python字典
item = {'website': '365工具网', 'rank': 1}
# json.dumps之后
item = json.dumps(item,ensure_ascii=False)
print('转换之后的数据类型为:',type(item))
print(item)
输出结果如下:
转换之后的数据类型为:最后对上述方法做简单地总结,如下表所示:{"website": "365工具网", "url": "www.365tools.cn"}
| 方法 | 作用 |
|---|---|
| json.dumps() | 将 Python 对象转换成 JSON 字符串。 |
| json.loads() | 将 JSON 字符串转换成 Python 对象。 |
| json.dump() | 将 Python 中的对象转化成 JSON 字符串储存到文件中。 |
| json.load() | 将文件中的 JSON 字符串转化成 Python 对象提取出来。 |