Simple JSON stays undefined - javascript

I have an AJAX call that get's a simple JSON back on success, writing the returned JSON into the variable named data.
The returned JSON has been generated within PHP through:
echo json_encode(array('message'=>0);.
Back in my javascript console I'm logging the output of data with console.log(data);. The output is {"message":0}, which seems correct.
However, if I try to log console.log(data.message); I am getting message: undefined.
What am I doing wrong in accessing this pretty basic JSON object?
I've been reading some articles about how to move through JSON object, e.g. https://www.tutorialspoint.com/json/json_overview.htm but I can't find my mistake.
Hopefully you can point me into the right direction :)
Thank you :)

You have to do JSON.parse(result) first to make it an object, because at the moment you're trying to access message property of a string.
You know there are 2 JSON functions in javascript, right...?
// returns string representation of the object
JSON.stringify(object);
// returns a new object built from the string
JSON.parse(object_stringified);

Related

Object property displayed in the console, but returns undefined when I read it

article is an object variable.
console.log("reesult id " + JSON.stringify(article));
When I do this, it outputs me: [{"Id":43}]
and when I do:
console.log(article[0]);
It outputs me {"Id":43}
but now... HOW to get just 43?
Because when I type:
console.log(article[0].Id);
, It returns me undefined instead of 43. Pf.
So, HOW to get 43?
It is very difficult because I made researches and it does not work as well.
I am unable to comment to so posting as an answer.
Your solution looks fine.
Could you print the output for
JSON.stringify(article[0].id)
Sequelize has it's own way how to return objects in json so you should try using their way to handle with objects since you are using that library.
This is from Sequelize documentation.
For any response object that resulted from a query, you can extract
only the data you want by appending .get({plain:true}) the the
response.
Here you have a link to that documentation so you can read more for that since you are not providing any code to us.

How to create JSon object and store data in it

I am trying to consume data from an API using REST call . I've succeeded to get data from the API .
I am having different rest call , I created different function for everyone .
I would like to know if I can store these data using JSon
it works perfect and gets all the Rest call but I would like to store them in JSon objects data to get it as a result in order to show it .
What I have done .
- I created a new object called Json
- I looped to consume data using REST call .
- but whenever I got this data , I have problems to store them .
var jsonObj = []; //declare object
$.each(data.results, function(i,item){ // on this line
jsonObj.push({id:item.conceptUuid ,
MedicalImage: item.dataURI ,
title: item.title ,
description: item.description ,
});
$htmlstring.append($('<li/>').append($('<img/>').attr('src',jsonObj.MedicalImage) ));
$htmlstring.append("<div class='title'> title: " + jsonObj.title
+ "<br> description : "+ jsonObj.description +
"</div>")
});
$('#result').html($htmlstring);
The function should take a query string as an argument, and the server returns data as JSON.
Can you show me an example how to do this using jQuery Storing data in JSON object to avoid multiple calls ?
JSON stands for "JavaScript Object Notation". It is a format designed for serialized network transport, not for runtime memory storage. Inside JavaScript a JSON object is simply an object. The "Object Notation" part describes the fact that even though JSON is transferred as a string over the network, it's structure can still be read — both by software and humans — as a regular, plain JS object.
In example, JSON.stringify({foo:'one', bar:'two'}) would return '{"foo":"one", "bar":"two"}', a string representation of the JavaScript object ready for HTTP transfer. Likewise, calling JSON.parse('{"foo":"one", "bar":"two"}') on receiving end would convert it back to the original object structure with datatypes intact. Read more about JSON here.
Other than this suspected misunderstanding of what JSON is and isn't, I'm not really sure what you mean by save. I take it you are haveing trouble reading the data and not getting anything on screen. This could be due to a number of things, primarily:
You might not be working with a de-serialized JSON string. In this case the data or data.results argument above might still be JSON, in which case you need to call JSON.parse(data) on it first in order to iterate over the properties of the data object.
You might be trying to use out-of-scope variables since you are dealing with already existing variables ($htmlstring) inside of the success callback. If so you should read up on the JavaScript scope model
If none of this helps, I recommend you open up the JavaScript console in your browser, run the code and check for error messages. If any, you should post them here to better your chances of a good answer.
Good luck!

JSON.parse not evaluating JSON strings properly

I am using JSON.parse to parse this JSON string
[{"created_at":"2012-01-24T22:36:21Z","name":"joe","age":42,"updated_at":"2012-01-24T22:36:21Z"}]
However I am simply getting this result as the output:
[object Object]
Which shouldn't be the result. I am using this within the Cappuccino framework. Does anyone know what I am doing wrong here?
[object Object] is what objects display when you call toString on them. It looks like you're taking your result and trying to call obj.toString()
Also, your JSON is an array with one element in it, so to verify that your result is correct, you can access the name property on the [0] index:
obj[0].name // should be "joe".
var text = '[{"created_at":"2012-01-24T22:36:21Z","name":"joe","age":42,"updated_at":"2012-01-24T22:36:21Z"}]';
var obj = JSON.parse(text);
alert(obj[0].name); //alerts joe
DEMO
Or get rid of the array, since it's not really doing much
var text = '{"created_at":"2012-01-24T22:36:21Z","name":"joe","age":42,"updated_at":"2012-01-24T22:36:21Z"}';
var obj = JSON.parse(text);
alert(obj.name); //still joe
DEMO
This is an array because it's in square brackets - [] - remove these and it should work...
Even though this is 'syntactically' correct the parser sees this as an array (which is a type of object) but won't do the work on it the way you'd expect.
Also for future reference:
Try to lint it, and see if your syntax is messed up: http://jsonlint.com/
This is an old subject, but nonetheless, I spent hours trying to figure out what was going on. So, hopefully this will help someone else in the future.
My issue was setting up a simple ajax call, and doing something with the resultset from said ajax call. However, no matter what I did, I couldn't get the json resultset to an object.
I ended up stepping through everything in the debugger window and noticed old code that was no longer active was showing up on the sidebar (dom detail). So, my data had been cached. I cleared the cache, and boom! Everything worked.

parse json object from server side

IN my web service,I return one json object in the method:
{name:'xx'}
I use the ajax to send the request,then parse them using the 'eval'
onComplete:function(req){
var data=eval(req.responseText);
//do something according data
}
However,I can not get the 'data'.
When I retrun the following string:
[{name:'xx'}]
It worked,and I get the 'data' as an array.
Through google,I know that it is caused by the '{' in the return string.
So I wonder if there is no way to retrun a json object ?
Use JSON.parse or jquery's $.parseJSON - if you use jquery - instead of eval.
Also, if you do use jquery, you can take advantage of the built-in ajax method that automaticly retrieves and parses the response as a json object : $.getJson.
If you still don't want to modify your "logic", you can try to eval your response with added brackets : var data = eval('(' + req.responseText + ')');
Have a read of this blog post on JSON hijacking. The author explains the issue your running into
You might have seen code like the following when related to JSON:
eval('('+JSON_DATA+')');
Notice the beginning and ending parenthesis, this is to force
JavaScript to execute the data as an object not a block statement
mentioned above. If JavaScript did attempt to execute JSON data
without the parenthesis and the JSON data did in fact begin with “{”
then a syntax error would occur because the block statement would be
invalid.
...more info on why...
Rather than adding () around your JSON response, you should be using JSON.parse or $.parseJSON like gion_13 has said. Eval isn't the way to go.
Also, like quentin said in the comments, you need to change the JSON you're returning as it's invalid. You need to quote your key as well as your value.
It worked,and I get the 'data' as an array.
That's what it's supposed to do. [] is the syntax for declaring an array. If you want the inner object, then just return {name: 'XX'}.

How to convert JSON string to javascript objects?

I searched for this topic, and I can't seem to find the right way to parse the JSON string to read the objects.
Here is my code
$.getJSON("<url>",
function(data) {
alert("success!"+data);
});
outputs:
success![object Object],[object Object],[object Object],[object Object]
Firebug shows correct response, and when I click JSON tab I see all the objects.
Thanks!
When a JSON string is parsed, it is turned into a Javascript object. If you use a string method on an object, the string [object Object] is returned.
You need to use object property access methods instead (e.g. alert(data.somekey);).
Don't use alert() for debugging in cases like this if you have Firebug available. Use console.log(data) and you will get direct insights into your JSON data.
In this case you'd have realized that there's absolutely nothing wrong :D .
JSON = JavaScript Object Notation precisely because it is the way to declare object literals in JavaScript. The data parameter is already a Javascript object (in your case an array of objects) that you can access as:
data[index].fieldname
enter your json string here, and click on the created tree view On the top left you will see how you can access it
link text

Categories

Resources