[Python] JSON 資料的序列化和反序列化 示範

在 Python 中內建了 json 的套件,要使用非常簡單:

序列化

將 Python 物件轉換為字串:
    
import json

data = {
    "id": 1,
    "name": "Ruyut",
    "email": "a@ruyut.com",
    "hobbies": ["coding", "reading"],
    "married": False,
    "motorcycles": True,
    "cars": None,
    "preferences": {
        "theme": "dark",
        "language": "python"
    },
}

json_str = json.dumps(data)
print(json_str)
    

範例輸出:
    
{"id": 1, "name": "Ruyut", "email": "a@ruyut.com", "hobbies": ["coding", "reading"], "married": false, "motorcycles": true, "cars": null, "preferences": {"theme": "dark", "language": "python"}}
    

如果想要自動換行,讓 JSON 方便閱讀,可以使用下面的方式輸出:
    
# json_str = json.dumps(data)
json_str = json.dumps(data, indent=2)
    

範例輸出:
    
{
  "id": 1,
  "name": "Ruyut",
  "email": "a@ruyut.com",
  "hobbies": [
    "coding",
    "reading"
  ],
  "married": false,
  "motorcycles": true,
  "cars": null,
  "preferences": {
    "theme": "dark",
    "language": "python"
  }
}
    

比較需要注意的是 Python 資料類型轉換為 JSON 格式時的差別:
  • True -> true
  • False -> false
  • None -> null

反序列化

將 JSON 字串轉換為 python 物件:
    
import json

json_str = """
    {
      "id": 1,
      "name": "Ruyut",
      "email": "a@ruyut.com",
      "hobbies": [
        "coding",
        "reading"
      ],
      "married": false,
      "motorcycles": true,
      "cars": null,
      "preferences": {
        "theme": "dark",
        "language": "python"
      }
    }
"""

data = json.loads(json_str)

    

要取得單獨的資料也很簡單:
    
print(data["email"])  # a@ruyut.com
print(data["preferences"])  # {'theme': 'dark', 'language': 'python'}
print(data["preferences"]["language"])  # python
    

新增、修改、刪除:
    
# 加入 age
data["age"] = 30

# 刪除 married
del data["married"]

# 更新 email
data["email"] = "b@ruyut.com"
    

範例輸出:
    
{
  "id": 1,
  "name": "Ruyut",
  "email": "b@ruyut.com",
  "hobbies": [
    "coding",
    "reading"
  ],
  "motorcycles": true,
  "cars": null,
  "preferences": {
    "theme": "dark",
    "language": "python"
  },
  "age": 30
}
    

留言