📖 Python 学习笔记
python对象转换为json数据
引入json模块,使用dumps和dump实现对象转换为json字符串
import json
def objetc_to_json():
books = [
{
"name":"朝花夕拾",
"price":100.0
},{
"name": "老人与海",
"price": 70.0
}
]
result = json.dumps(books,ensure_ascii = False)
print({"result":result,"type":type(result)})
with open("jsonfile.json","w",encoding="utf-8") as bs:
json.dump(books,bs,ensure_ascii= False)
- dumps方法直接将对象转化为json,enable_ascii属性控制是否使用ascii码
- dump方法可以接受一个文件指针,并将解析完的json字符串存入到文件内
json数据转化为python对象
import json
def json_to_object():
json_str = '[{"name": "朝花夕拾", "price": 100.0}, {"name": "老人与海", "price": 70.0}]'
obj = json.loads(json_str)
print({"obj":obj,"type":type(obj)})
with open("jsonfile.json","r",encoding="utf-8") as bs:
bs_obj = json.load(bs)
print({"bs_obj": bs_obj, "type": type(bs_obj)})
- 打开jsonfile.json文件时,要注意编码要和写入时的编码一致
- load 方法直接从文件中获取字符串并转为对象
|