parse json object from server side - javascript

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'}.

Related

Simple JSON stays undefined

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

What is the right way to store JavaScript source code in a json object?

I want to edit JavaScript in a textarea and store it back into a JavaScript object. For example I have this object:
var item1 = {
'id' : 1,
'title':'title',
'sourcecode' : "alert('hallo')"
};
If I would change the content to alert("hallo") or a even more complex example does this break my object?
I would think there is some escape function like this https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/escape. But it is marked as deprecated.
So if this is deprecated what would be the right way for storing complex JavaScript code into a JavaScript object?
Should I use stringify ?
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
The JSON.stringify() method converts a JavaScript value to a JSON
string, optionally replacing values if a replacer function is
specified, or optionally including only the specified properties if a
replacer array is specified.
This does not read like there is an automated escape build in.
If you need to send the data to a server, I'd say you should encodeURI your sourceCode, and then JSON.stringify the entire object. When retreiving data from the server, you should decodeURI the sourceCode

JS: convert string into object

I have code
data = "{isShowLoginPopup:true,newFavOfferId:1486882}";
I want to convert it into JS object (not in JSON) and use it in this way:
data.newFavOfferId = ...
How can I do this?
If your source is trusted, the simplest solution is to use eval :
data = eval('('+data+')');
If you don't trust the source, then you'd better specify what you can have and parse the string manually (not terribly hard if you have only one level of properties for example).
Another solution (depending on your real data) would be to change your data into JSON by inserting the missing quotes :
data = JSON.parse(datareplace(/({|,)\s*([^:,}{]+)\s*(:)/g,'$1"$2"$3'));
just remove the quotes
data = {
isShowLoginPopup:true,
newFavOfferId:1486882
};
Fiddle: http://jsfiddle.net/QpZ4j/
just remove quotes "" from the
data = "{isShowLoginPopup:true,newFavOfferId:1486882}";
DEMO
Whilst on the surface this looks like JSON data, it's malformed and therefore it does not work directly with JSON.parse(). This is because JSON objects require keys to be wrapped in quotes...
therefore:
"{isShowLoginPopup:true,newFavOfferId:1486882}"
as valid JSON should be:
"{\"isShowLoginPopup\":true,\"newFavOfferId\":1486882}"
So what you have there in fact IS a JavaScript object, not JSON, however the problem you have is that this is a JavaScript object as a string literal. If this is hard coded, then you need to just remove the " from the beginning and end of the string.
var data = {isShowLoginPopup:true,newFavOfferId:1486882};
If this object is serialized and requires transmission from/to a server etc, then realistically, it needs to be transmitted as a JSON formatted string, which can then be de-serialized back into a JavaScript object.
var data = JSON.parse("{\"isShowLoginPopup\":true,\"newFavOfferId\":1486882}");

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!

missing ] after element list parsing JSON

Executing that:
$.post(
"/url/to/method",
{ },
function(data){
var obj2 = eval("("+$(data).children()+")");
// OR var obj = $.evalJSON($($(data).children())); // Jquery-json
$body = $("#AAA");
$body.html(obj.fied);
},
"xml"
);
while turn into a "missing ] after element list" (at row 5 or 6) error in firebug. The JSON output from method has been validated with jsonlint.com/
Probably is obvious but please I'm newbie around AJAX/JSON. Thanks
What is probably happening is that your $.post call is returning a JSON object already. jQuery will try to detect JSON automatically and parse it for you. When you call eval on a JSON object like this, you see this error. Sneaky! Just use the data object as is.
Use the JSON.parse method, or be sure to include a space next to your parens before passing it to eval...
eval(" (" + data + ") ");
Are you writing this in the .NET 2.0? If so try constructing your data into a query string rather than passing a JSON object.
Example:
var1=alma&var2=user
Where "var1" and "var2" are the names of the parameters that your webmethod expects. Pass this using the post.. Data: {querystring}
I ran into issues when passing JSON to webservice in 2.0.
Good Luck
Turns out that jQuery will try to figure out if the result is JSON and parse it automatically, but in this case data is already a JavaScript object and not a JSON string waiting to be parsed. So you can use this object as it is instead of using eval() and JSON.parse.

Categories

Resources