如何在 Python 和 Node.js 之間進行 JSON 資料通訊?
JSON 可以縮寫為 JavaScript 物件表示法 (JavaScript Object Notation)。它是一個基於文字的檔案,用於在程式語言之間傳輸和儲存資料。Python 程式語言透過內建的 JSON 包支援它。它的文字以帶引號的字串格式給出,其中包含在大括號 {}內的鍵值對,與字典相同。
要在 Python 中使用 JSON,必須在 Python 指令碼中匯入 JSON 包。JSON 包提供了多種方法,其中一種方法是 dumps()。它用於將 Python 元組物件轉換為 Java 物件,以便在 Python 之間進行通訊。
Node.js 內建了 JSON 物件來解析 JSON 資料到 JavaScript。JSON 中的 parse() 函式用於將 JSON 物件轉換為 JavaScript 字串。
要在 Node.js 和 Python 之間進行JSON 資料通訊,我們使用 HTTP 請求和響應。
安裝 Flask 模組
首先,我們必須安裝所需的模組才能在 Python 和 Node.js 之間建立通訊。
pip install flask
輸出
以下是安裝 Flask 模組的輸出。
Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/ Collecting flask Downloading Flask-2.2.3-py3-none-any.whl (101 kB) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Installing collected packages: flask Successfully installed flask-2.2.3
安裝 requests 模組
現在,我們必須安裝 requests 模組才能在 Python 和 Node.js 伺服器之間進行通訊。
npm install request-promise
步驟
接下來,我們必須按照以下步驟在 Python 和 Node.js 之間進行 JSON 資料通訊。
首先,我們必須在工作環境中匯入 Python 中可用的 JSON 模組。
import json
現在,我們將使用 Python 建立字典格式的資料,然後使用 json 模組的 dumps() 函式將 Python 資料轉換為 json 資料,程式碼如下:
import json data = {"Language":["Python","Java","C"], "Year":[2000,2004,2009]} json_data = json.dumps(data) print(json_data) print(type(json_data))
執行以上程式碼後,將生成以下輸出:
{"Language": ["Python", "Java", "C"], "Year": [2000, 2004, 2009]} <class 'str'="">
在此步驟中,我們將使用 Node.js 中可用的 parse() 函式將 json 資料轉換為 JavaScript。程式碼如下:
const json_string = '{"name": "John", "age": 30}'; const data = JSON.parse(json_string);
現在,我們必須在 Python 模組和 Node.js 之間建立連線。
import requests import json data = {"Language":["Python","Java","C"], "Year":[2000,2004,2009]} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} response = requests.post('https://:3000', data=json.dumps(data), headers=headers)
在此步驟中,我們將建立 JavaScript 來接收來自 Python 到 Node.js 的資料。
const http = require('http'); const server = http.createServer((req, res) => { let data = ''; req.on('data', chunk => { data += chunk; }); req.on('end', () => { const json_data = JSON.parse(data); console.log(json_data); }); res.end('OK'); }); server.listen(3000, () => { console.log('Server listening on port 3000'); });