How do I parse a json response from a GET request - javascript

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;

Related

Sending data from NodeJS to the client by using Ajax calls

I increase a value at the server by running an Ajax call and want to update my UI after doing this
function increaseHitpoints(){
$.ajax({
type: 'GET',
url: 'http://localhost:8888/incHp/2312'
}).done(function (data) {
$("#txtHitpoints").html(data);
});
}
In my app.js I read a JSON file, manipulate the value, write it back to the file and return it to the client
app.get('/incHp/:id', function (req, res) {
var database = './database.json';
fs.readFile(database, 'utf8', function (err, data) { // read the data
var json = JSON.parse(data);
var users = json.users;
var hitpoints;
users.find(u => {
if (u.id === Number(req.params.id)) { // get the user by id
u.hitpoints++;
hitpoints = u.hitpoints;
}
});
json = JSON.stringify(json);
fs.writeFile(database, json, (err) => { // update the JSON file
// -> missing part here <-
});
});
});
what do I have to pass into the missing part if I want to return the new value? The new value would be hitpoints
I tried res.send(hitpoints); but it seems this function wants to return a status code, not a value.
If you send a numerical value, it will be observed as an HTTP response code
https://expressjs.com/en/api.html#res
But you can send your hitpoints as a string res.send(hitpoints.toString())or as json res.send({hits: hitpoints});
Depends on what format you want your response to be. I prefer using JSON. So in JSON case you would do this:
fs.writeFile(database, json, (err) => {
res.status(200).json({yourKey: yourValue});
});
Then you can access the JSON object in your frontend:
$("#txtHitpoints").html(data.yourKey);

Get intents, entities, contexts and all data

In the case, the actually conversation-simple have one function with all the values, but the function update every time if flows conversation.
I want create one function or other form to be able to capture all that data that is currently on the data.
In the case have Intents, context, entities, etc.
conversation.message(payload, function(err, data) {
if (err) {
return res.status(err.code || 500).json(err);
}
return res.json(updateMessage(payload, data));
});
});
The data inside updateMessage parameter have all I need, but if I create other function and try get this values, does not work.
In the case I use the values and get with app.js for open some REST webservice.
I try it:
function login (req, res) {
numberOrigin = null;
sessionid = null;
var dataLogin = {
data: { "userName":"xxxxx","password":"xxxxx","platform":"MyPlatform" },
headers: { "Content-Type": "application/json" }
};
client.registerMethod("postMethod", "xxxxxxxxxxxxxxx/services/login", "POST");
client.methods.postMethod(dataLogin, function (data, response) {
if(Buffer.isBuffer(data)){
data = data.toString('utf8');
console.log(data);
var re = /(sessionID: )([^,}]*)/g;
var match = re.exec(data);
var sessionid = match[2]
console.log(sessionid);
}
});
}
function openRequest(data, sessionid, numberOrigin ){
//console.log(data); dont show the values.. show the data response of login
var dataRequest = {
data: {"sessionID": sessionid,
"synchronize":false,
"sourceRequest":{
"numberOrigin":numberOrigin,
"description": JSON.stringify(data.context.email) } },
headers: { "Content-Type": "application/json" }
};
numberOrigin +=1;
client.post("xxxxxxxxxxxxxxxxxx/services/request/create", dataRequest, function (data, response) {
if(Buffer.isBuffer(data)){
data = data.toString('utf8');
console.log(data);
}
});
}
function updateMessage(res, input, data, numberOrigin) {
var email = data.context.email; // this recognize but this function is responsible for other thing
if (email === 'xxxxxxxxxxxx#test.com') {
console.log(data);
login(data);
openRequest(data, sessionid, numberOrigin)
}
}
In case, I just want get the values with my app.js for use inside REST. I got it with ajax but everything on the client side (index.html), and that made me show my credentials, so I decided to do it in REST for security my code..
If have some form to solved this, please let me know.
If have other form to do it, I'll be happy to know.
Thanks advance.
The issue is likely that you need to write to the response object res.. In the updateMessage function the response is passed in. In order for data to be sent back to the browser you need to write to the response. I have a demo app which calls the weather channel to get the weather based on an intent, similar to what you are trying to do with your login function. Please take a look at this code
https://github.com/doconnor78/conversation-simple-weather/blob/master/app.js#L130
You will need to pass the original res (response) object into the appropriate function and then write data to the response (res) once you get it from the third party service.

Use generated json object instead d3.json

I missed a lot of time that to resolve this problem but unlucky. I know how to render d3 tree with external file, but how to do that with generated object. I'm getting Json object thru this code:
$.when($.getJSON('data/clinical.json'), $.getJSON('data/industry.json'))
.then(function (a, b) {
return $.extend(a[0], b[0]);
})
.then(function (data) {
var json = JSON.stringify(data);
console.log('['+ json +']');
and have added json to d3.json
treeJSON = d3.json(json, function (error, treeData) {
so whole part of code looks like:
function load() {
$.when($.getJSON('data/clinical.json'), $.getJSON('data/industry.json'))
.then(function (a, b) {
return $.extend(a[0], b[0]);
})
.then(function (data) {
var json = JSON.stringify(data);
console.log('['+ json +']');
// Get JSON data
treeJSON = d3.json(json, function (error, treeData) {
the most interesting part is that console log self defined such as right string:
[{"text":"Alas","icon":"icons/tree.png","children":[{"text":"CDISC","children":[{"text":"SDTM","children":[{"text":"SDTM 3.1.1","icon":"icons/file.png"},{"text":"SDTM 3.1.3","icon":"icons/file.png"},{"text":"SDTM 3.2","icon":"icons/file.png"}]},{"text":"ADaM"},{"text":"CDASH"}]},{"text":"CDISC"},{"text":"BRIDG"}]}]
but I'm still getting an error:
GET http://localhost:63342/testMerg/%7B%22text%22:%22Alas%22,%22icon%22:%22…SH%22%7D]%7D,%7B%22text%22:%22CDISC%22%7D,%7B%22text%22:%22BRIDG%22%7D]%7D 404 (Not Found)
I've tried to use string method from some example which I found somewhere here:
.then(function (data) {
var json = JSON.stringify(data);
// Get JSON data
treeData = JSON.parse( data );
but got an error
Uncaught SyntaxError: Unexpected token o
so I give up... could anybody help me?
The problem arises because data is an Object and your trying to parse the object. But JSON.parse function expects a string as the parameter.
You can either directly assign treeData = data. (No need for parsing).
Or else you should try stringifying the object and then parse the stringified json.
var json = JSON.stringify(data);
treeData = JSON.parse(json);
var data = {"text":"Alas","icon":"icons/tree.png","children":[{"text":"CDISC","children":[{"text":"SDTM","children":[{"text":"SDTM 3.1.1","icon":"icons/file.png"},{"text":"SDTM 3.1.3","icon":"icons/file.png"},{"text":"SDTM 3.2","icon":"icons/file.png"}]},{"text":"ADaM"},{"text":"CDASH"}]},{"text":"CDISC"},{"text":"BRIDG"}]};
//treeData = data;
json = JSON.stringify(data);
console.log(JSON.parse(json));

JSON.parse unexpected result in node.js

I am sending a http request to a website (from node.js) which returns a JSON object. I get the expected JSON file. However when I parse the JSON text, my program isn't able to do anything.
var URL = 'http://www.omdbapi.com/?t=' + movie + '&y=&plot=short&r=json';
requestify.get(URL).then(function (response) {
console.log(response.getBody()); // It prints correctly
var jsonBody = response.getBody();
var jsonObject = JSON.parse(jsonBody);
if (jsonObject.Response == 'False') {
console.log('False'); //not printed
} else {
console.log('true'); //Not printed
}
});
Sample JSON output:
{"Response":"False","Error":"Movie not found!"}
response.body is the raw text response. response.getBody() should already return a parsed JSON response as long as you have the correct content-type header specified.
Sending a JS object to JSON.parse results in a SyntaxError.

Undefined parameter when returning data from jQuery.post to PHP

I am trying to return data from a database and populate a text field after the user enters an ID in the first text box. Currently I had the code working as long as the user did not enter a space in the ID number. Now I am attempting to allow that use case. My PHP code returns a json encoded array with three fields: first_name, last_name, and full_name.
When I use console.log(data) to view the data being returned I receive the following:
{"first_name":"Test","last_name":"Test","full_name":"Test Test"}
However in my code, I try to write data.full_name in a .val() nothing is populated, and when use the console.log I get an error saying "undefined".
Here is the whole jQuery Code:
$("#ID").blur(function () {
var params = {};
params.ID = encodeURIComponent($(this).val());
$.post("getter.php", params, function ( data ) {
if (!data) {
$("input[name=username]").val("User Not Found");
} else {
$("input[name=username]").val(data.full_name);
$("input[name=username]").attr("readonly", true);
}
});
});
Any help you can offer would be much appreciated.
Force jQuery to read the returned data as json:
$("#ID").blur(function () {
var params = {};
params.ID = encodeURIComponent($(this).val());
$.post("getter.php", params, function ( data ) {
if (!data) {
$("input[name=username]").val("User Not Found");
} else {
$("input[name=username]").val(data.full_name);
$("input[name=username]").attr("readonly", true);
}
}, "json"); // <- json forced
});
and then make sure your returned data is in proper json format (for example with json_encode in php)
Use trim() to remove spaces.
Then you can check if the parameter value is_numeric(), and if false, set a default value.

Categories