简体   繁体   中英

How to retrieve specific value from list of Json Object in NodeJS

I'm trying the below code to retrieve the executionArn but I'm getting this error

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

How to get executionArn or stateMachineArn from each record? Any help would be much appreciated.

console.log(data) - Output

{
  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'
}

Code:

  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);
    });

  });

data is an object and executions inside it is an array, so try this

data.executions.foreach(function (execution) {
  console.log('executionArn', execution.executionArn)
  console.log('stateMachineArn', execution.stateMachineArn)
})
executions.map(e=>{
   // access it here
   let a =  e.executionArn;
 });

The provided output (data) is not a valid JSON object,

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

For valid JSON, it should look like

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

for it to be iterated correctly.

If the data is from the server (API), stringify the dates before returning them, and the values could be found by

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM