Search code examples
node.jsjsonapistringify

how to iterate json with parentheses


I have an api that is returning a json data but that data is wrapped in curly brackets and I am not able to iterate the response. I tried to convert that into string, sliced the brackets and then tries t o convert that back into json but that didn''t work as expected.

The response I receive is below

{
  data: [
    { id: 'Price', result: [Object], errors: [] },
    { id: 'rsi', result: [Object], errors: [] },
    { id: 'ema14', result: [Object], errors: [] },
    { id: 'ema24', result: [Object], errors: [] },
    { id: 'ema55', result: [Object], errors: [] },
    { id: 'ema100', result: [Object], errors: [] },
    { id: 'ema200', result: [Object], errors: [] }
  ]
}

The below is what I tried and facing error

.then( response => {
    var string = JSON.stringify(response.data)
    var objectstr = string.slice(1,-1)
    let objectJson = json.parse(objectstr)
    console.log(response.data);
})

without converting it into json response.data[0] gives undefined. if I convert that into string and remove the brackets it doesn't parse that string back into JSON.

ReferenceError: json is not defined
    at D:\Crypto\API Learning\Api.js:63:22
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

What I want is to get data from response.data as response.data[0].id


Solution

  • there is no need to remove parenthesis, and you are using lower case of JSON.parse here ..let objectJson = json.parse(objectstr).

    Try below code assuming that response contains plain object:

    var response= {
      data: [
        { id: 'Price', result: [Object], errors: [] },
        { id: 'rsi', result: [Object], errors: [] },
        { id: 'ema14', result: [Object], errors: [] },
        { id: 'ema24', result: [Object], errors: [] },
        { id: 'ema55', result: [Object], errors: [] },
        { id: 'ema100', result: [Object], errors: [] },
        { id: 'ema200', result: [Object], errors: [] }
      ]
    };
    
    var string = JSON.stringify(response)
    let objectJson = JSON.parse(string)
    console.log(objectJson.data); // here you can iterate over data array.
    

    enter image description here