JSON:轻量级的数据交换格式;键值对集合。类似于python中的dic.
来源于慕课网学习实战脚本笔记:
import json
def python_to_json():
""" 将python对象转换成json"""
d = {
'name':'python书籍',
'price':62.5,
'is_valid':True
}
# rest1 = json.dumps(d) 优化打印方式
rest = json.dumps(d, indent=4)
print(rest)
def json_to_python():
"""将json转换为python"""
data ='''
{
"name": "python书籍",
"origin_price": 88,
"pub_date": "2018-4-14 17:00:00",
"store": ["京东", "淘宝"],
"author": ["张三","李四","Jhone"],
"is_valid": true,
"is_sale": false,
"meta": {
"isbn": "abd-123",
"pages": 300
},
"desc": null
}
'''
rest = json.loads(data)
print(rest)
print(rest['name'])
def json_to_python_from_file():
""" 从json文件中读取内容,并转换成python对象"""
f =open('./book1.json', 'r', encoding='utf-8')
s = f.read()
rest = json.loads(s)
print(rest['name'])
f.close()
if __name__ =='__main__':
#python_to_json()
#json_to_python()
json_to_python_from_file()
网友评论