,python,node.js,arrays,aws-lambda,aws-sdk"/>

首页 > 解决方案 > 不同时间的不同错误消息“SyntaxError: Unexpected token in JSON at position”在 JSON.parse ()"

问题描述

我是 JavaScript 和 AWS 的新手。我从主 Lambda 函数(假设是父 lambda)的中间行调用了一个单独的 Lambda 函数(假设是子 lambda),并使用父 lambda 中子 lambda 的返回值。

我的子 lambda 在 Python 3.6 中实现,父 lambda 在 Node.js 12.x 中实现。

我有一个 3d 数组分配给父 lambda 中的变量“img”。如果满足条件,我通过将 Payload 作为 3d 'img' 数组传递来调用子 lambda。
在子 lambda 中,我使用数组值创建图像,预处理图像(添加一些过滤器并裁剪图像)通过以下代码转换回 3d 数组。

imageList = croppedImage.tolist()

然后使用下面的代码交换其中的一些元素(请注意 imageList 数组的大小为 224x224x3)

for i in range(224):
   for j in range(224):
       a=imageList[i][j][0]
       imageList[i][j][0]=imageList[i][j][2]
       imageList[i][j][2]=a

然后使用下面的代码将其返回给父 lambda。

return {
      "returnArray": imageList
}

最后用返回的数组替换“img”变量。

父 lambda 中的代码块如下。我使用第 1 行将其转换为 JSON 对象。

const AWS = require('aws-sdk');
AWS.config.region = 'ap-southeast-2';
var lambda = new AWS.Lambda();

exports.handler = async (event, ctx, callback) => {
    //////////code lines for other operations////////////

    let img = //Line A - 3d array with RGB values of an image;
    let body1;
    if(condition){
        console.log("BEGIN");
        var params = {
                FunctionName: 'childFunction', // child lambda function written in Pyton 3.6
                InvocationType: 'RequestResponse',
                Payload: JSON.stringify({ "sendImg" : img})
            };
            lambda.invoke(params, function(err, data) {
                if (err) {
                console.log(err);
                } else {
                console.log('Returned '+ data.Payload); //Line B
                let body1;
                if(typeof(data.Payload) == 'object') {
                    body1 = data.Payload;
                } else {
                    body1 = JSON.parse(data.Payload); //Line 1
                }
                img = body1["returnArray"];
                }
            }).promise();
    }
    ////////Rest of the code///////////////////////
};

这是 python lambda 函数(子 lambda)

import json
import cv2
import numpy as np

def lambda_handler(event, context):
    array=event['sendImg']
    for i in range(224):
        for j in range(224):
            a=array[i][j][0]
            array[i][j][0]=array[i][j][2]
            array[i][j][2]=a
    new_image = np.array(array, np.uint8)
    
    image = new_image
    image1 = image.copy()
    lab = cv2.cvtColor(image1, cv2.COLOR_BGR2LAB)
    l,a,b = cv2.split(lab)

    #perform thresholding
    m,thresh = cv2.threshold(a,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    i=0
    maxArea=0
    for c in contours:
        i+=1
        areaC = cv2.contourArea(c)
        if maxArea<areaC:
            maxArea=areaC
            maxIndex=i
        
    i=0
    image3=image.copy()
    for c in contours:
        i+=1
        if i==maxIndex:
            rect = cv2.minAreaRect(c)
            (x, y), (width, height), angle = rect
            box = cv2.boxPoints(rect)
            box = np.int0(box)
            cv2.drawContours(image3,[box],0,(0,0,0),-1)
    
    image4=image.copy()
    gray = cv2.cvtColor(image3, cv2.COLOR_BGR2GRAY)
    m,mask = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    mean = cv2.mean(image4, mask=mask)
    diff = [127-mean[0],127-mean[1],127-mean[2]]

    rows,cols,c = image.shape
    image5=image.copy()

    for i in range(rows):
        for j in range(cols):
            k = image5[i,j]
            if(k[0]+diff[0]>255):
                image5[i,j][0] = 255
            elif(k[0]+diff[0]<0):
                image5[i,j][0] = 0
            else:
                image5[i,j][0] = image5[i,j][0]+diff[0]
                
            if(k[1]+diff[1]>255):
                image5[i,j][1] = 255
            elif(k[1]+diff[1]<0):
                image5[i,j][1] = 0
            else:
                image5[i,j][1] = image5[i,j][1]+diff[1]
                
            if(k[2]+diff[2]>255):
                image5[i,j][2] = 255
            elif(k[2]+diff[2]<0):
                image5[i,j][2] = 0
            else:
                image5[i,j][2] = image5[i,j][2]+diff[2]

    #crop
    image2 = image5.copy()
    lab = cv2.cvtColor(image2, cv2.COLOR_BGR2LAB)
    l,a,b = cv2.split(lab)

    #perform thresholding
    m,thresh = cv2.threshold(a,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

    image6 = image5.copy()
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cv2.drawContours(image6, contours, -1, (0,255,0), 1)

    i=0
    maxArea=0
    for c in contours:
        i+=1
        areaC = cv2.contourArea(c)
        if maxArea<areaC:
            maxArea=areaC
            maxIndex=i
        
    i=0
    image7=image5.copy()
    image8=image5.copy()
    for c in contours:
        i+=1
        if i==maxIndex:
            rect = cv2.minAreaRect(c)
            (x, y), (width, height), angle = rect
            x=round(x)
            y=round(y)
            width=round(width)
            height=round(height)
            box = cv2.boxPoints(rect)
            box = np.int0(box)
            cv2.drawContours(image7,[box],0,(0,255,0),2)
            src_pts = box.astype("float32")
            dst_pts = np.array([[0, height-1],
                                [0, 0],
                                [width-1, 0],
                                [width-1, height-1]], dtype="float32")
            M = cv2.getPerspectiveTransform(src_pts, dst_pts)
            warped = cv2.warpPerspective(image8, M, (width, height))
            croppedImage = cv2.resize(warped, (224,224), interpolation = cv2.INTER_AREA)
    imageList = croppedImage.tolist()
    for i in range(224):
        for j in range(224):
            a=imageList[i][j][0]
            imageList[i][j][0]=imageList[i][j][2]
            imageList[i][j][2]=a
    print("returnArray ",imageList) #Line 3
    return {
        "returnArray": imageList
    }

问题: 在不同时间使用相同的“img”数组(A 行)运行程序时,第 1 行给出不同的错误消息。有时它不会给出任何错误消息并成功完成程序。

一些错误消息如下。

一次错误消息 -

{
    "errorType": "SyntaxError",
    "errorMessage": "Unexpected token ] in JSON at position 1****",
    "code": "SyntaxError",
    "message": "Unexpected token ] in JSON at position 1",
    "time": "2021-07-19T09:50:14.678Z",
    "stack": [
        "SyntaxError: Unexpected token ] in JSON at position 1",
        "    at JSON.parse (<anonymous>)",
        "    at Response.<anonymous> (/var/task/index.js:81:30)",
        "    at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:369:18)",
        "    at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:106:20)",
        "    at Request.emit (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:78:10)",
        "    at Request.emit (/var/runtime/node_modules/aws-sdk/lib/request.js:688:14)",
        "    at Request.transition (/var/runtime/node_modules/aws-sdk/lib/request.js:22:10)",
        "    at AcceptorStateMachine.runTo (/var/runtime/node_modules/aws-sdk/lib/state_machine.js:14:12)",
        "    at /var/runtime/node_modules/aws-sdk/lib/state_machine.js:26:10",
        "    at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:38:9)"
    ]
}

另一个时间的错误消息 -

{
    "errorType": "SyntaxError",
    "errorMessage": "Unexpected token , in JSON at position 3",
    "code": "SyntaxError",
    "message": "Unexpected token , in JSON at position 3",
    "time": "2021-07-19T09:10:41.553Z",
    "stack": [
        "SyntaxError: Unexpected token , in JSON at position 3",
        "    at JSON.parse (<anonymous>)",
        "    at Response.<anonymous> (/var/task/index.js:81:30)",
        "    at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:369:18)",
        "    at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:106:20)",
        "    at Request.emit (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:78:10)",
        "    at Request.emit (/var/runtime/node_modules/aws-sdk/lib/request.js:688:14)",
        "    at Request.transition (/var/runtime/node_modules/aws-sdk/lib/request.js:22:10)",
        "    at AcceptorStateMachine.runTo (/var/runtime/node_modules/aws-sdk/lib/state_machine.js:14:12)",
        "    at /var/runtime/node_modules/aws-sdk/lib/state_machine.js:26:10",
        "    at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:38:9)"
    ]
}

你可以看到上面两个错误中的token和position是不同的。

有时它不会给出任何错误消息并成功完成程序。

我在子 lambda 中打印了输出 3d 数组,并在父 lambda(B 行)中返回了 3d 数组(data.Payload)。

python lambda (child lambda) 中的第 3 行打印正确的 3d 数组。
python lambda 中第 3 行的输出 -
returnArray [[[113, 111, 110], [66, 60, 55], [51, 44, 38], [53, 44, 38], [59, 48, 42 ], [63, 53, 47], [68, 61, 56], [73, 62, 56], [74, 64, 58], [75, 65, 59], [80, 70, 64], [84, 75, 67], [86, 77, 68],...

这是正确的。

但是 B 行给出了不同的结果。
有时 data.Payload 的输出在一开始就错过了数组的某个部分。

下面是一些示例输出(B 行输出)。
返回 [131, 69, 20], [130, 70, 28], [125, 69, 34], [118, 59, 26], [81, 22, 0],...

返回 133], [186, 146, 110], [172, 125, 86], [123, 72, 43], [88, 37, 14], [150, 100, 54], [180, 126, 74 ], [179, 121, 64],...

但它应该是;
返回 {"returnArray": [[[113, 111, 110], [66, 60, 55], [51, 44, 38], [53, 44, 38], [59, 48, 42], [63 , 53, 47], [68, 61, 56],...

为什么从子 lambda 返回的数组有时在父 lambda 中不同?

谢谢。

标签: pythonnode.jsarraysaws-lambdaaws-sdk

解决方案


推荐阅读