JSON模块基本使用
程序员文章站
2024-02-03 10:09:34
...
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import json
# json.loads 把json字符串转成 python 对象
json_string = '''
{
"a":"x",
"b":"y"
}
'''
data = json.loads(json_string)
print(data)
print(type(data))
# json.dumps 把 python 对象转 json 字符串
data = {
"a":"x",
"b":"y"
}
json_string = json.dumps(data)
print(json_string)
print(type(json_string))
# 从 json 文件中获取数据
# 读取字符串
with open('09-test.json','r',encoding='utf-8') as f:
json_string = f.read()
data = json.loads(json_string)
print(data)
print(type(data))
# json.load 从 json 文件中获取数据
with open('09-test.json','r',encoding='utf-8') as f:
data = json.load(f)
print(data)
print(type(data))
# json.dump 把python数据写入到 json文件中
data = {
"a":"x",
"b":"y",
"parents":{
"mother":"妈妈",
"father":"爸爸"
}
}
with open('09-test2.json','w',encoding='utf-8') as f:
# indent 缩紧
# ensure_ascii 中文写入
json.dump(data,f,indent=4,ensure_ascii=False)
上一篇: Python基础之常用模块(二)