python与json转换
2020-12-13 04:12
标签:def class color ati des zha taobao tor dong python与json转换 标签:def class color ati des zha taobao tor dong 原文地址:https://www.cnblogs.com/zsjlovewm/p/11106231.htmlimport json
def python_to_json():
"""将python对象转换为json"""
d = {
‘name‘:‘python书籍‘
}
rest = json.dumps(d,indent = 4)
print (rest)
def json_to_python():
""""将json转换为python"""
data = ‘‘‘
{
"name":"Python book",
"origin_price":66,
"pub_date":"2018-4-15 17:00:00",
"store":["jingdong","taobao"],
"author":["zhangshan","lisi","jhone"],
"is_valid":true,
"is_sale":false,
"meta":{
"isbn":"abc-123",
"pages":300
},
"desc":null
}
‘‘‘
rest = json.loads(data)
print(rest)
print(rest[‘name‘])
def json_to_python_from_file():
""""从文件读取内容并转换成python文件"""
f = open(‘./venv/static_/book.json‘,‘r‘,encoding=‘utf-8‘)#只读模式
s = f.read()
print(s)
rest = json.loads(s)
print(rest[‘name‘])
f.close()
if __name__==‘__main__‘:
python_to_json()
# json_to_python()
#json_to_python_from_file()