利用Python互轉Json資料格式
阿新 • • 發佈:2019-02-18
一、將Python物件轉換成json物件
import json
def python_to_json():
""" 將python物件轉換成json """
d = {
'name': 'python書籍',
'price': 62.3,
'is_valid': True
}
rest = json.dumps(d, indent=4) //設定首行縮排
print(rest)
二、將json轉換成python
def json_to_python(): """ 將json轉換成python """ data = ''' { "name": "Python書籍", "origin_price": 66, "pub_date": "2018-4-14 17:00:00", "store": ["京東", "淘寶"], "author": ["張三", "李四", "Jhone"], "is_valid": true, "is_sale": false, "meta": { "isbn": "abc-123", "pages": 300 }, "desc": null } ''' rest = json.loads(data) print(rest) print(rest['name'])
三、從檔案讀取內容,並轉換成python物件
def json_to_python_from_file():
""" 從檔案讀取內容,並轉換成python物件 """
f = open('./static/book.json', 'r', encoding='utf-8') 以只讀的格式,utf-8 的編碼讀取
s = f.read()
print(s)
rest = json.loads(s)
print(rest['name'])
f.close() //開啟檔案後一定要關閉