简体   繁体   中英

How do I parse a json response from a GET request

How do I go about parsing this json response so I can grab the email_address keys and their respective values. it is being returned in this function. I have tried response.content.email_address which just returns undefined. It must be really simple, I just can't seem to parse it properly.

Thanks

function (error, response) {
  if ( error ) {
    console.log( error );
  } else {
    console.log( response );
  }

Json Response

content: '{"meta":{"pagination":{}},"results":[{"id":"1405904834","status":"ACTIVE","fax":"","addresses":[],"notes":[],"confirmed":false,"lists":[{"id":"1395617465","status":"ACTIVE"}],"source":"Site Owner","email_addresses":[{"id":"d39bf7e0-a2f9-11e7-909a-d4ae528442b5","status":"ACTIVE","confirm_status":"NO_CONFIRMATION_REQUIRED","opt_in_source":"ACTION_BY_OWNER","opt_in_date":"2017-09-26T20:32:33.000Z","email_address":"anders@kitson.org"}],"prefix_name":"","first_name":"Anders","middle_name":"","last_name":"Kitson","job_title":"","company_name":"","home_phone":"","work_phone":"","cell_phone":"","custom_fields":[],"created_date":"2017-09-26T20:32:33.000Z","modified_date":"2017-09-26T20:32:33.000Z","source_details":""},{"id":"1474126978","status":"ACTIVE","fax":"","addresses":[],"notes":[],"confirmed":false,"lists":[{"id":"1395617465","status":"ACTIVE"}],"source":"Site Owner","email_addresses":[{"id":"62874c40-a398-11e7-a559-d4ae5292bb50","status":"ACTIVE","confirm_status":"NO_CONFIRMATION_REQUIRED","opt_in_source":"ACTION_BY_OWNER","opt_in_date":"2017-09-27T15:27:34.000Z","email_address":"test@example.com"}],"prefix_name":"","first_name":"","middle_name":"","last_name":"","job_title":"","company_name":"","home_phone":"","work_phone":"","cell_phone":"","custom_fields":[],"created_date":"2017-09-27T15:27:34.000Z","modified_date":"2017-09-27T15:27:34.000Z","source_details":""}]}'

You can use JSON.parse(response) You can then save it in a variable so you can access the data from there.

function(error, response) {
  if (error) {
    console.log(error);
  } else {
    var data = JSON.parse(response);
    console.log(data.content.email_address) // This should print the value
  };
});

I had to end up doing something like this to get one of the email addresses, so i guess I will have to run a for loop or something to get all of them.

var data = JSON.parse(response.content);
var dataParsed = data.results[0].email_addresses[0].email_address;

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