JSON 解析

JSON(JavaScript Object Notation)是目前各系統間資料交換最普遍的一種資料格式,用途非常廣泛,例如全球各種資料開放平臺上透過 Web API 下載的資料,或是像 MongoDB 這種 NoSQL 類型資料庫所儲存的資料格式都是 JSON 格式。JSON 是一種字串型態,格式定義請參考 https://www.json.org

拿到 JSON 字串後要做的事情是 JSON 解析,解析的意思是分析 JSON 格式是否正確並且對映到一個好處理的資料結構上,例如字典或是陣列,這樣就不需要透過麻煩的子字串處理才能取得 JSON 中需要的資料,MicroPython 已經內建 JSON 解析器,只要一行程式碼就解析完成了,例如:

import ujson

str = '''
{
    "name": "David",
    "age": 30
}
'''

obj = ujson.loads(str)
print(obj['name'])   # Prints: David

上面這段程式碼中的 JSON 是以大刮號開頭,因此對映出來的資料結構是字典,若是中刮號開頭,對映出來的資料結構就是陣列,然後用個迴圈就可以把整個陣列中想要的資料列出來,如下:

import ujson

str = '''
[
    {
        "name": "David",
        "age": 30
    },
    {
        "name": "Betty",
        "age": 27
    }
]
'''

obj = ujson.loads(str)
for el in obj:
    print(el['name']) # Prints: David Mei

如果是透過呼叫 Web API 取得的 JSON 字串,還可以直接使用 urequests 函數庫中內建的 json() 來解析,如下:

import urequests
import ujson

## 這裡要先連上網路

url = 'https://raw.githubusercontent.com/kirkchu/mongodb/main/demo.json'
res = urequests.get(url=url)
for el in res.json():
    print(f'name:{el["name"]},age:{el["age"]}')

res.close()

將陣列或字典結構轉成 JSON 字串

有的時候我們需要將一個陣列或是字典轉成 JSON 字串,原因是有些 Web API 在上傳資料時會要求以 JSON 作為資料格式,或是當我們想要將這個陣列或是字典內容儲存在檔案中的時候,轉成字串也比較方便處理。範例如下:

import ujson

obj = {
    "title": "鉛筆",
    "price": 10
}

str = ujson.dumps(obj)
print(str)

# Prints: {"price": 10, "title": "鉛筆"}

如果網址中有中文的話,必須將中文重新編碼,否則呼叫時所有中文都會變成亂碼。MicroPython 沒有內建的編碼函數,必須自己實做,程式碼如下。

def url_encode(s):
    result = ''
    for c in s:
        if '0' <= c <= '9' or 'a' <= c <= 'z' or 'A' <= c <= 'Z' or c in '-._~/:&=':
            result += c
        else:
            utf8_bytes = c.encode('utf-8')
            for byte in utf8_bytes:
                result += '%' + ("%02X" % byte)
    return result

使用方式如下。順便處理回來資料中的中文問題。

url = url_encode('http://172.20.10.2/中文路徑')
res = urequests.get(url)
data = res.content.decode('utf-8')
jsonObj = json.loads(data)

★本系列收錄於「第一次就上手」選單

發表迴響