python——读写JSON文件

定义:json(JavaScript object notation,java脚本对象标注符),是一种轻量级的数据交换格式,它开始被用于JavaScript语言,后被推广为不同程序之间数据共享的一种技术标准
把python数据转化为json格式(带格式的字符串)的过程叫做序列化;把json格式转化为python数据类型的过程叫做反序列化

json类型 python类型
object dict
array list
string str
number(int) int
true true
false false
null none

示例:

import json                            #导入json模块
json_file = {'one':1,'two':2,'three':3}#定义字典对象
print(json_file)                       #字典数据结构

输出结果为:{‘one’: 1, ‘two’: 2, ‘three’: 3}

import json                            	   #导入json模块
json_file = {'one':1,'two':2,'three':3}    #定义字典对象
new_json_file = json.dumps(json_file)      #通过dumps把字典对象转为json类型
print(new_json_file)                       #字典数据结构

输出结果为:{“one”: 1, “two”: 2, “three”: 3}

import json                            	   #导入json模块
json_file = {'one':1,'two':2,'three':3}    #定义字典对象
json_file_demo = json.dumps(json_file)     #通过dumps把字典对象转为json类型
new_json_file = json.loads(json_file_demo) #把json格式转为python字典格式 
print(new_json_file)                       #字典数据结构

输出结果为:{‘one’: 1, ‘two’: 2, ‘three’: 3}

一、将数据写入json文件

import json

json_file = {'apple':15,'pear':13,'orange':12}

with open('D:/demo.json','w') as f:
	f.write(json.dumps(json_file))
	print('保存成功')

在这里插入图片描述

二、读取json文件

import json

with open('D:/demo.json','r') as f:
	data = f.read()
	json_data = json.loads(data)
	print(json_data)

输出结果为:{‘apple’: 15, ‘pear’: 13, ‘orange’: 12}

还可以根据key获取values值

import json

with open('D:/demo.json','r') as f:
	data = f.read()
	json_data = json.loads(data)
	print(json_data['apple'])

输出结果为:15

正在尝试写博客,把会的分享给你们,如有写的不好的地方,希望指点一下,喜欢的朋友们请点个赞,谢谢!

猜你喜欢

转载自blog.csdn.net/Woo_home/article/details/88618591