Search code examples
node.jsjsonstringify

Obtain data from JSON object with NODE JS


I have a response from a webservice like this:

[{"record_id":"63","date":"2021-04-12","acept":"1","name":"John","document":"1","passport":"","phone":"999999999","sign":"[document]","activity":"2"}]

There is a var called response that stores that response. How do I get the "name" and the "phone" from this?

I tried to do JSON.stringify(response) in order to get somehow the info but I don't know what to do next. Is the response a JSON or just a String?? Should I do JSON.stringify or JSON.parse to be able to work with this? Thanks a lot


Solution

  • To check to see whether this is a JSON object or string, run console.log(typeof response). If it logs object, then this is already a JSON object! You don't have to do anything, and can get attributes out of it like any other object. (For instance, to get the name attribute, you can run response[0]["name"].) If it logs string, then you'll have to run JSON.parse(response) and save that to a variable to parse the string and turn it into an object.