【问题标题】:How to retrieve specific value from list of Json Object in NodeJS如何从 NodeJS 中的 Json 对象列表中检索特定值
【发布时间】:2021-09-02 08:53:44
【问题描述】:

我正在尝试下面的代码来检索 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);
    });

  });

【问题讨论】:

  • console.log(data) 的输出是什么?请注意,输入不是有效的 JSON。
  • 更新了我的帖子 - 请检查这个 console.log(data) - 输出
  • data 看起来像是一个 JavaScript 对象,而不是 JSON。应该不用JSON.parse
  • 如果我不使用 JSON.parse 那么它给我一个 data.forEach 不是一个函数:(
  • 可能是因为data 是一个没有该功能的对象。尝试改用data.executions.forEach

标签: javascript node.js json foreach


【解决方案1】:

提供的输出(数据)不是有效的 JSON 对象,

{...
  startDate: 2021-06-17T13:43:39.817Z,
  stopDate: 2021-06-17T13:43:53.667Z
}

对于有效的 JSON,它应该是这样的

{...
  "startDate": "2021-06-17T13:43:39.817Z",
  "stopDate": "2021-06-17T13:43:53.667Z"
}

为了它被正确地迭代。

如果数据来自服务器(API),则在返回之前将日期字符串化,并且可以通过以下方式找到值

  data.executions.map(execution=>{
      let arnValue = execution.executionArn;
      console.log(arnValue);
  })

【讨论】:

【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
    executions.map(e=>{
       // access it here
       let a =  e.executionArn;
     });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-10
      • 2021-07-02
      • 2016-01-31
      • 2019-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多