Json Handling With Python

2022-11-28

筆記使用 Python 關於 Json (JavaScript Object Notation) 的優雅處理之道 😗

logo

說明

Method Usage
json.load file or binary file instance
json.loads string, byte, bytearray instance

Data From Local File (json.load)

data.json

[
  {
    "id": "1",
    "gid": "722",
    "name": "木木梟",
    "types": "草, 飛行",
    "name_en": "Rowlet",
    "name_jp": "モクロー"
  },
  ...
]

app.py

import json

with open(r'.\data.json', encoding='utf8') as f:
    pokemons = json.load(f)

Data From Web (json.loads)

Pokemon.json

{
  "Pokemons": [
    {
      "Pno": 1,
      "Name": "Bulbasaur",
      "Name_CT": "妙蛙種子",
      "HP": 45,
      "Atk": 49,
      "Def": 49,
      "SpAtk": 65,
      "SpDef": 65,
      "Speed": 45,
      "Type": [
        "Grass",
        "Poison"
      ]
    },
  ...
  ]
}

app.py

import reuqests
res = requests.get('https://raw.githubusercontent.com/sdwh/Data/master/Json/Pokemon.json')

pokemons = json.loads(res.text)

pokemons['Pokemons'][0]

Write to Json (json.dumps)

app.py

data = {
  'name': 'eddie',
  'description': 'dba'
  'tools': [
    'ssms',
    'sql profiler'
  ]
}

with open(r'.\memo.json', 'w', encoding='utf8') as f:
    f.write(json.dumps(data, indent = 4, ensure_ascii=False))

memo.json

{
    "name": "eddie",
    "description": "dba",
    "tools": [
        "ssms",
        "sql profiler"
    ]
}