Step1:Json是什么
JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式。具有数据格式简单,读写方便易懂等很多优点。
许多主流的编程语言都在用它来进行前后端的数据传输,大大的简化了服务器和客户端的开发工作量。相对于 XML 来说,更加的轻量级,更方便解析,因此许多开发者都遵循 Json 格式来进行数据的传输和交换。
Json 的数据格式其实就是 Python 里面的字典格式,里面可以包含方括号括起来的数组,也就是 Python 里面的列表。
Step2:Json 模块的四个方法
- dumps():将dict数据转化成json数据(Python里是str类型)
- loads():将json数据转化成dict数据(Python里是dict类型)
- load():读取json文件数据,转成dict数据
- dump():将dict数据转化成json数据后写入json文件
Step3:Python代码实现
import json
def dict_to_json():
dict1={}
dict1['name']='tom'
dict1['age']=20
dict1['sex']='male'
print(dict1)
jsons=json.dumps(dict1)
print(jsons)
print(type(jsons))
def json_to_dict():
jsons = '{"name": "tony", "age": 28, "sex": "male", "phone": "123456", "email": "loadkernel@126.com"}'
dict1= json.loads(jsons)
print(dict1)
print(type(dict1))
def dict_to_json_write_file():
dict = {}
dict['name'] = 'tom'
dict['age'] = 10
dict['sex'] = 'male'
print(dict)
with open('test.json', 'w') as f:
json.dump(dict, f)
def json_file_to_dict():
with open('test.json', 'r') as f:
dict1 = json.load(f)
print(dict1)
print(type(dict1))
if __name__ == '__main__':
dict_to_json()
json_to_dict()
dict_to_json_write_file()
json_file_to_dict()
运行结果如下:
{'name': 'tom', 'age': 20, 'sex': 'male'}
{"name": "tom", "age": 20, "sex": "male"}
{'name': 'tony', 'age': 28, 'sex': 'male', 'phone': '123456', 'email': 'loadkernel@126.com'}
{'name': 'tom', 'age': 10, 'sex': 'male'}
{'name': 'tom', 'age': 10, 'sex': 'male'}