json可以透過特定的格式去儲存任何資料(字串,數字,陣列,物件)
- Json可以接受的資料類型
- 數字 (整數或浮點數)
- 字串 (請用 “” 括號)
- 布林函數 (boolean) (true 或 false)
- 陣列 (請用 [] )
- 物件 (請用 { } )
- NULL
{"":"","":"","":""}
["","",""]
("","","")
[{"":"","":"","":""},{"":"","":"","":""},{"":"","":"","":""}]
json可以接受的資料類型
import json
print(json.dumps({"name":"yiru","phone":"0912345678","age":99})) #dict
print(json.dumps(["computer","TV"])) #list
print(json.dumps(("python","java"))) #tuple
print(json.dumps("hihi")) #str
print(json.dumps(True)) #bool
範例:
import json
person = {
"name": "mary", #字串
"age": 50, #整數
"married": True, #bool
"pets": ("mimi","ruru"), #tuple
"car": None, #無
"children": [ #陣列
{"nikename": "mary", "age": 23}, #物件
{"nikename": "john", "age": 26}
]
}
#轉成JSON字串:
people = json.dumps(person)
print(people)
縮排-讓資料看起來更整齊
#縮排indent
import json
person = {
"name":"judy",
"age" :55,
"married":True,
"pets":("mimi","ruru"),
"car":None,
"child":[
{"nikename":"candy","age":23},
{"nikename":"John","age":26}
]
}
people=json.dumps(person,indent=10)
print(people)
Yiru@Studio - 關於我 - 意如