如何在Python和Node.js之间传递JSON数据

如何在Python和Node.js之间传递JSON数据

以下文章介绍了如何在Python和Node.js之间传递JSON数据。假设我们正在使用Node.js应用程序,并且我们想要使用一个仅在Python中可用的特定库,或者相反。我们应该能够在一种语言中共享结果到另一种语言,并为此使用JSON,因为它是语言无关的。

方法:

  1. 为每种语言设置一个服务器,并使用JSON共享数据,使用GET和POST请求。
  2. 从Node.js调用一个Python后台进程,或者反过来,在两种情况下监听进程的stdout流。

项目结构:

下面所示的所有文件都与同一目录中的文件相同。

如何在Python和Node.js之间传递JSON数据

1. 使用服务器: 这与使用第三方API服务的方法类似,我们向远程服务器发出GET请求以获取数据,并向服务器发送POST请求以发送数据。唯一的区别是我们会在本地运行服务器(在所需的URL上也可以在远程服务器上工作)。

Node.js to Python: 当我们在node.js中工作并且想要在python中处理一些数据时。

在下面的示例中,我们将为Python设置一个服务器,并从node.js发出请求。我们使用 Flask 微框架,因为这是在Python中设置服务器和在Node.js中发出请求的最简单方法,我们需要一个 request 包。

模块安装:

  • 使用以下命令安装Python的flask模块:
pip install flask
  • 使用以下命令安装Node.js的request模块:
npm install request-promise

示例: 计算包含整数的数组的总和,并将结果返回给Node.js

pyserver.py

from flask import Flask, request 
import json  
   
# Setup flask server 
app = Flask(__name__)  
  
# Setup url route which will calculate 
# total sum of array. 
@app.route('/arraysum', methods = ['POST'])  
def sum_of_array():  
    data = request.get_json()  
    print(data) 
  
    # Data variable contains the  
    # data from the node server 
    ls = data['array']  
    result = sum(ls) # calculate the sum 
  
    # Return data in json format  
    return json.dumps({"result":result}) 
   
if __name__ == "__main__":  
    app.run(port=5000)

使用以下命令运行 服务器

python pyserver.py

这将在 http://127.0.0.1:5000/ 启动服务器。现在我们从Node.js向 http://127.0.0.1:5000/arraysum 发起POST请求。

talk.js

var request = require('request-promise'); 
  
async function arraysum() { 
  
    // This variable contains the data 
    // you want to send  
    var data = { 
        array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
    } 
  
    var options = { 
        method: 'POST', 
  
        // http:flaskserverurl:port/route 
        uri: 'http://127.0.0.1:5000/arraysum', 
        body: data, 
  
        // Automatically stringifies 
        // the body to JSON  
        json: true
    }; 
  
    var sendrequest = await request(options) 
  
        // The parsedBody contains the data 
        // sent back from the Flask server  
        .then(function (parsedBody) { 
            console.log(parsedBody); 
              
            // You can do something with 
            // returned data 
            let result; 
            result = parsedBody['result']; 
            console.log("Sum of Array from Python: ", result); 
        }) 
        .catch(function (err) { 
            console.log(err); 
        }); 
} 
  
arraysum(); 

通过以下命令运行此脚本。

node talk.js

输出:

{ result: 55 }
Sum of Array from Python:  55

Python转Node.js: 当我们在Python中工作,并且想在Node.js中处理一些数据时。

在这里,我们将反转上述过程,并在Node.js中使用 express 来启动服务器,并在Python中使用 request 包。

模块安装:

  • 使用以下命令为Python安装request模块:
pip install requests
  • 使用以下命令为NodeJS安装express和body-parser模块:
npm install express
npm install body-parser

nodeserver.js

var express = require('express'); 
var bodyParser = require('body-parser'); 
  
var app = express(); 
  
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: false })); 
  
app.post("/arraysum", (req, res) => { 
  
    // Retrieve array form post body 
    var array = req.body.array;   
    console.log(array); 
  
    // Calculate sum 
    var sum = 0; 
    for (var i = 0; i < array.length; i++) { 
        if (isNaN(array[i])) { 
            continue; 
        } 
        sum += array[i]; 
    } 
    console.log(sum); 
  
    // Return json response 
    res.json({ result: sum }); 
}); 
  
// Server listening to PORT 3000 
app.listen(3000); 

使用以下命令运行 服务器

node nodeserver.js

这将在 http://127.0.0.1:3000/ 处启动服务器。现在我们将在Python中向 127.0.0.1:3000/arraysum 发送POST请求。

talk.py

import requests 
  
# Sample array 
array = [1,2,3,4,5,6,7,8,9,10] 
  
# Data that we will send in post request. 
data = {'array':array} 
  
# The POST request to our node server 
res = requests.post('http://127.0.0.1:3000/arraysum', json=data)  
  
# Convert response data to json 
returned_data = res.json()  
  
print(returned_data) 
result = returned_data['result']  
print("Sum of Array from Node.js:", result)

通过以下命令运行此脚本。

python talk.py 

输出:

{'result': 55}
Sum of Array from Node.js: 55

2. 使用后台进程: 在下面的示例中,我们将通过从Node.js生成一个Python进程并反之亦然来进行通信,并监听stdout流。

Node.js 到 Python: 从node.js调用python进程。它涉及以下步骤:

  1. 调用python进程,并将JSON数据作为命令行参数传递。
  2. 在Python中读取数据,对其进行处理,并以JSON格式输出到stdout流中。
  3. 再次从node.js读取输出流并处理JSON数据。

arraysum.py

import sys, json 
  
# Function to calculate the sum of array 
def arraysum(arr): 
    return sum(arr) 
  
# Get the command line arguments 
# and parse it to json 
data = json.loads(sys.argv[1]) 
  
# Get the required field from 
# the data 
array = data['array'] 
  
# Calculate the result 
result = arraysum(array) 
  
# Print the data in stringified 
# json format so that we can 
# easily parse it in Node.js 
newdata = {'sum':result} 
print(json.dumps(newdata))

现在Python将处理数组的总和并将其打印到标准输出(stdout),如下面的代码所示。

caller.js

const spawn = require('child_process').spawn; 
  
// Initialise the data 
const data = { 
  array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
} 
  
// We need to stringify the data as  
// python cannot directly read JSON 
// as command line argument. 
let stringifiedData = JSON.stringify(data); 
  
// Call the python process and pass the 
// data as command line argument. 
const py = spawn('python', ['arraysum.py', stringifiedData]); 
  
resultString = ''; 
  
// As the stdout data stream is chunked, 
// we need to concat all the chunks. 
py.stdout.on('data', function (stdData) { 
  resultString += stdData.toString(); 
}); 
  
py.stdout.on('end', function () { 
  
  // Parse the string as JSON when stdout 
  // data stream ends 
  let resultData = JSON.parse(resultString); 
  
  let sum = resultData['sum']; 
  console.log('Sum of array from Python process =', sum); 
});

通过以下命令运行这个脚本:

node caller.js

输出:

Sum of array from Python process = 55

Python 到 Node.js: 从 Python 调用 Node.js 进程。步骤基本与上述提到的 Python 和 Node.js 互换其角色保持一致。

arraysum.js

// Function to calculate sum of array 
function arraysum(arr) { 
  let sum = 0; 
  for (var i = 0; i < arr.length; i++) { 
    if (isNaN(arr[i])) { 
      continue; 
    } 
    sum += arr[i]; 
  } 
  return sum; 
} 
  
// Get the command line arguments and 
// parse it to json 
var data = JSON.parse(process.argv[2]); 
  
// Get the required field form the data. 
array = data['array']; 
  
// Calculate the result. 
var sum = arraysum(array); 
  
// Print the data in stringified json 
// format so that we can easily parse 
// it in Python 
const newData = { sum } 
console.log(JSON.stringify(newData));

现在从Python运行这个Node.js进程。

文件名:caller.py

from subprocess import Popen, PIPE 
import json 
  
# Initialise the data 
array = [1,2,3,4,5,6,7,8,9,10] 
data = {'array':array} 
  
# Stringify the data. 
stingified_data = json.dumps(data) 
  
# Call the node process and pass the 
# data as command line argument 
process = Popen(['node', 'arraysum.js',  
        stingified_data], stdout=PIPE) 
  
# This line essentially waits for the  
# node process to complete and then 
# read stdout data 
stdout = process.communicate()[0] 
  
# The stdout is a bytes string, you can 
# convert it to another encoding but 
# json.loads() supports bytes string 
# so we aren't converting 
  
# Parse the data into json 
result_data = json.loads(stdout) 
array_sum = result_data['sum'] 
print('Sum of array from Node.js process =',array_sum)

请使用以下命令运行此脚本。

python caller.py

输出:

Sum of array from Node.js process = 55

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程