Python-68-Json可以接受的資料類型

json可以透過特定的格式去儲存任何資料(字串,數字,陣列,物件)

  • Json可以接受的資料類型
  1.  數字 (整數或浮點數)
  2. 字串 (請用 “” 括號)
  3. 布林函數 (boolean) (true 或 false)
  4. 陣列 (請用 [] )
  5. 物件 (請用 { } )
  6. 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 - 關於我 - 意如