JSON是一种轻量级的数据交换格式,易于阅读和编写
主要知识点
- import json---->使用json函数需要导入自带的json库
- json.dumps----->方法:将python对象编码成json字符串,我们可以在这里格式化字符串
- json.loads----->方法:将已编码的json字符串解码为python对象
案例
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import json
#将python对象编码成json字符串
def py_to_jsonstr():
dict = {"name":"heting","age":23}
json_str = json.dumps(dict)
print(json_str)
#将python对象编码成json字符串,并格式化
def py_to_jsonstr_format():
dict = {"name": "heting", "age": 23}
json_str_1 = json.dumps(dict,indent=4,sort_keys=True)
print(json_str_1)
#将json字符串解码为python对象
def jsonstr_to_py():
dict = {"name":"heting","age":23}
json_str = json.dumps(dict)
py_json = json.loads(json_str)
print(py_json)
print(type(py_json))
if __name__=="__main__":
py_to_jsonstr()
py_to_jsonstr_format()
jsonstr_to_py()
网友评论