首页 > 解决方案 > 如何从 NodeJS 中的 Json 对象列表中检索特定值

问题描述

我正在尝试下面的代码来检索executionArn但我收到了这个错误

Error [SyntaxError]: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)

如何从每条记录中获取executionArnstateMachineArn ?任何帮助将非常感激。

console.log(data) - 输出

{
  executions: [
    {
      executionArn: 'arn:aws:states:us-east-2:12222:execution:test:dcb689bc',
      stateMachineArn: 'arn:aws:states:us-east-2:12222:stateMachine:test-sm',
      name: 'test-name',
      status: 'SUCCEEDED',
      startDate: 2021-06-17T13:43:39.817Z,
      stopDate: 2021-06-17T13:43:53.667Z
    },
    {
      executionArn: 'arn:aws:states:us-east-2:12222:execution:test:sd32dsdf',
      stateMachineArn: 'arn:aws:states:us-east-2:12222:stateMachine:test-sm',
      name: 'test-name1',
      status: 'SUCCEEDED',
      startDate: 2021-06-17T13:43:39.817Z,
      stopDate: 2021-06-17T13:43:53.667Z
    }
  ],
  nextToken: 'aadfdfdf'
}

代码:

  stepfunctions.listExecutions(params, function(err, data) {
    if (err) console.log(err, err.stack); 
    else     
    console.log(data)
    //console.log(data.executions[0].executionArn)
    data = JSON.parse(data);
    data.forEach(function(result) {
        var arnValue = result.executions.executionArn;
        console.log(arnValue);
    });

  });

标签: javascriptnode.jsjsonforeach

解决方案


data 是一个对象,其中的执行是一个数组,所以试试这个

data.executions.foreach(function (execution) {
  console.log('executionArn', execution.executionArn)
  console.log('stateMachineArn', execution.stateMachineArn)
})

推荐阅读