Python基础之JSON
JSON是一种高效的数据交换格式,Python中提供了非常方便的支持。
json模块
内置模块json提供了JSON相关的操作。在Python中,可以将一个JSON字符串转换成JSON对象(其实就是dict),也可以将JSON对象(dict)转换为JSON字符串。例如:
import json
# Convert a dict to JSON string
dic1 = {'name': 'xiaoming', 'age': 20, 'sex': 'm'}
str = json.dumps(dic1)
print(str)
print(type(str))
# Convert a dict to formatted JSON string
str = json.dumps(dic1, sort_keys=True, indent=4, separators=(',', ': '))
print(str)
print(type(str))
# Convert a JSON string to dict
j = json.loads(str)
print(j)
print(type(j))
运行结果:
D:\work\python_workspace\python_study\venv\Scripts\python.exe D:/work/python_workspace/python_study/basic_13/test_json.py
{"name": "xiaoming", "age": 20, "sex": "m"}
<class 'str'>
{
"age": 20,
"name": "xiaoming",
"sex": "m"
}
<class 'str'>
{'age': 20, 'name': 'xiaoming', 'sex': 'm'}
<class 'dict'>
Process finished with exit code 0