JSON.parse unexpected result in node.js - javascript

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.

Related

Correct way to handle the data from a post with JQuery

I have an issue converting the data coming from a server with post with JQuery because of the data received from the server is a "type of" [object Object]
Notes: the data received from the server is supposed to be a JSON
I tried to convert directly the response from the server to JSON I have an error, thus I tried first to convert the response into a string and then into JSON but this fails as well, the code is the following:
// THE FOLLOWING CODE IS FROM A HTML PAGE
$('#login-form').submit(function(event){
event.preventDefault();
// Get some values from elements on the page:
let $form = $(this),
email = $form.find("input[name='email']").val(),
password = $form.find("input[name='password']").val(),
url = $form.attr('action');
// Send the data using post
let posting = $.post(url, {useremail: email, userpassword: password},
function(data, status, xhr){ // catch response from the server
let responseString = JSON.stringify(data); // convert response from [object Object] to String
let responseJSON = JSON.parse(responseString); // convert response string to JSON type
});
});
/// THE FOLLOWING CODE IS FROM THE SERVER SIDE
res.json({
status: 'some status',
message: 'some message'
});
The expected results are that the data is converted to a JSON dictionary
Your server is already sending the response in JSON, so on the frontend (Client side) there is no need to JSON.stringify() response and again using JSON.parse() on it.
Try to log data, you should be able to access the status and message directly using the data response.
So try removing the following line from your .js file
let responseString = JSON.stringify(data);
Instead, try
console.log(data.status);
console.log(data.message);
Check if you get the appropriate log on the browser console.
Use JSON.parse() so your code will look like this:
let responseJSON;
$('#login-form').submit(function(event){
event.preventDefault();
// Get some values from elements on the page:
let $form = $(this),
email = $form.find("input[name='email']").val(),
password = $form.find("input[name='password']").val(),
url = $form.attr('action');
// Send the data using post
let posting = $.post(url, {useremail: email, userpassword: password},
function(data, status, xhr){ // catch response from the server
let responseString = JSON.stringify(data); // convert response from [object Object] to String
responseJSON = JSON.parse(responseString); // convert response string to JSON type
});
});
console.log(responseJSON.message);
if(responseJSON.hasOwnProperty('message') {
console.log(responseJSON['message']);
} else {
console.log("'message' not found in response");
}
Both will work. And if by "Dictionary" you mean key-value pairs with unique keys, JSON object keys should always be unique. You can check whether a key exists in an object using the hasOwnProperty() method as described above.
As long as your server is returning valid JSON content, the data returned by jQuery POST will be a JavaScript JSON object you don't need to process, for example:
$.post(url, data, function(data, status, xhr) {
// data is a JSON object with the server response
let id = data.id;
alert("Your new post was saved with id: " + id);
});
Note how I access the data directly.
Please check this simple jsfiddle I created for a quick demo; it uses a dummy API to make a POST request:
https://jsfiddle.net/danyalejandro/x46wzjdy/11/

How to parse large nested json objects?

PasteBin JSON
I would like to get this as Object it says jsonlint is valid but parsing is not anyone help would appreciate
"Data":[{...},{...},] // structure build like this
when i try
JSON.parse(jsonparamter) <-- Uncaught SyntaxError: Unexpected token A in JSON at position 71
at JSON.parse (<anonymous>)
at <anonymous>:1:6
There are multiple levels of JSON encoded data so you will have to create a loop to decode the elements deeper in the JSON nest. Use the below code to see an example of accessing Data.Adress.Value in this dictionary
// set up urls and headers for making HTTP req
corsurl = 'https://cors-anywhere.herokuapp.com/'
jsonurl = 'https://pastebin.com/raw/vuecweML'
headerNames = ['Content-Type','Accept']
headerValues = [ 'application/json', 'application/json']
// Modular get request function that I use
function getRequest (baseRestURL, APIPath, headerNames, headerValues, callback) {
var completeRestURL = baseRestURL + APIPath
console.log('REST API URL: ' + completeRestURL)
var method = 'GET'
var url = completeRestURL
var async = true
var request2 = new XMLHttpRequest()
request2.onload = function () {
console.log('ONLOAD')
var status = request2.status // HTTP response status, e.g., 200 for "200 OK"
console.log(status)
console.log(request2.responseText)
var response = request2.responseText
return callback(response)
}
request2.open(method, url, async)
for (var i in headerNames) {
request2.setRequestHeader(headerNames[i], headerValues[i])
}
request2.send(null)
}
// Our code of interest
getRequest(corsurl, jsonurl, headerNames, headerValues, response => {
parsed = JSON.parse(response).Data //parse our data the first time, and get the data attribute from dictionary
objects = JSON.parse(parsed) // parse a second time ( as data is JSON encoded twice )
selection = JSON.parse(objects[0].Address)[0].Value // parse a third time and select an attribute
document.getElementById('result').innerHTML = selection // Add it to our html to display
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div id='result'> Loading </div>

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;

Uncaught TypeError: Cannot read property 'total' of undefined

I get a JSON from my response object so I do:
var json = JSON.parse(res.text);
I print the JSON and get JSON back. But when I retrieve the value inside json.body.value.total then it gives this error:
Uncaught TypeError: Cannot read property 'total' of undefined
I have no idea why. I pasted the value that receive from var json and printed on console and was able to retrieve total. But I cannot do it through the code. There is a JSON value total. Its just unable to recognize. On the console, it works but does not work in the code.
I get JSON back from my response object which I retrieve using response.text. I think it needs to change in parsable object but all it returns is undefined
it('returns http 200', function (done) {
chai
.request(baseUrl)
.get('/api/')
.set('Authorization', 'Basic abc')
.query({val:'hey'})
.end(function(err, res) {
expect(res).to.have.status(200);
var json = res.text;
console.log('val: '+ JSON.parse(json.body));
var val = json.body.value.total; //undefined
expect(val.to.be.above(0)); //fails
done();
});
});
The REST API that I built was returning the response.body but what worked is this:
var body = JSON.parse(json.body);
var obj = JSON.stringify(body);
var jsonObj = JSON.parse(obj);
The above looks ridiculous but thats what worked. json -> object -> json. It was finding trouble to figure out that its a json object.
The console was doing a good job but not the library that I was using.
The complete code is this:
it('returns http 200', function (done) {
chai
.request(baseUrl)
.get('/api/')
.set('Authorization', 'Basic abc')
.query({val:'hey'})
.end(function(err, res) {
expect(res).to.have.status(200);
var json = res.text;
var body = JSON.parse(json.body);
var obj = JSON.stringify(body);
var jsonObj = JSON.parse(obj);
var val = jsonObj.body.value.total;
expect(val.to.be.above(0));
done();
});
});
You're not assigning the parsed value to json.
var json = res.text;
should be
var json = JSON.parse(res.text);
You have to put you json string into JSON.Parse() and access the properties on the result of the Parse function.
You can't just access properties from a text.

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

Categories