JSON.parse throws error when I try to parse a valid JSON object. My issue is i'm receiving data from webservice and sometimes it works with parse and sometimes it doesn't not sure what is the reason why. I would expect JSON.parse to return same object if its a valid JSON object? or parse it if its a string.
var obj1= { Result: Inprogress };
var json = JSON.parse(obj1);
please help me with this understanding
What you have there is a JavaScript object. It doesn't need to be parsed because it's plain JavaScript syntax and JavaScript itself parses it. JSON is a serialization format.
The JSON.parse() method takes a string argument, like one retrieved from an ajax call or from local storage or some other source of data that only deals in string values.
Your JSON is malformed. A right JSON is
{ "Result": "Inprogress" }
You have forgotten the "" character in beginning and in end of each part of your JSON.
Related
I have below result returned from python script
{"a_paget_wilkes": "\/speaker\/a_paget_wilkes.json",
"aaron_clark": "\/speaker\/aaron_clark.json",
"aaron_dunlop": "\/speaker\/aaron_dunlop.json",
"aaron_ernst": "\/speaker\/aaron_ernst.json",
"aaron_hurst": "\/speaker\/aaron_hurst.json",
"abigail_miller": "\/speaker\/abigail_miller.json",
"abner_kauffman": "\/speaker\/abner_kauffman.json"}
So it is pretty well formatted JSON I believe. Javascript variable which has above data is called jsondata. Now in the chrome developer tool console when I try to access key valye pair by typing jsondata. I expect all keys to be listed as suggestion, but it shows me string properties like length, anchor, big, blink etc... instead
I tried even JSON.stringify first and then JSON.parse but still the same!!!
Any idea what is wrong in here?
jsondata is apparently a string containing your JSON, rather than a JavaScript object that would result from parsing your JSON.
To parse it, use JSON.parse.
I tried even JSON.stringify first and then JSON.parse but still the same!!!
JSON.stringify will take you in the wrong direction — it will wrap your entire string in a JSON string — and JSON.parse will only undo the JSON.stringify (recovering your original string), not parse your original string.
You need to call JSON.parse without calling JSON.stringify first.
I am trying to parse a JSON Array that I posted from the client side to a node based server.
the json object holding the array looks like this
customData : {
"playlist": [
"//www.youtube.com/embed/bxq6SofU_38?rel=0",
"//www.youtube.com/embed/Qyqchamz4EM?rel=0"
]
}
However when I try to access the data using customData.playlist[0], it returns that it cannot parse 'playlist' the console reports that it is undefined.
I checked my JSON using the JSONLint validator and it said that me JSON was valid. I must be missing something pretty simple any thoughts?
if you get data from client side you should parse that like this:
var parsed = JSON.parse(recievedData);
and then you have access them.
Whenever response comes from a server or client ,the result will be in string.. Coz you know strings are easier to transfer within networks... Try to use JSON.parse. console the typeof of customData .. It must be object.. Then only you can.. Get values..
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}");
I made a ajax call from my jsp to servlet. when I want to return string then it is working fine. But I want to send response as a String array then its not working. Is it possible that I can send string array from servlet as a ajax response.
String[] roleAccess=null;
response.setContentType("text/html");
try{
roleAccess=new String[23];
roleAccess[0]="";
roleAccess[1]="checked";
roleAccess[2]="";
response.getWriter().write(roleAccess.toString());---this part I need to change.
Send the ajax response in json format by encoding the array in json and return it.
You can use Gson and then encode your array like:
String jsonRoleAccess = new Gson().toJson(roleAccess, roleAccess.class);
response.getWriter().write(jsonRoleAccess);
// OR do a one liner:
response.getWriter().write(new Gson().toJson(roleAccess, roleAccess.class));
And on the Javascript end, you can access it as a json object
// Assuming you've read the ajax response into var roleAccess
var checked = roleAccess[1];
You want to marshall the array as a JSON data type. The format returned by Java's array class is not in a format that JavaScript understands.
You should also wrap your array inside of an Object because of a security issue of passing top-level arrays back as JSON.
See Why are top level json arrays a security risk
Write it out to JSON instead. Javascript can't understand the result of a Java array's toString() method ([Ljava.lang.String;#5527f4f9), but I know it can understand JSON.
If you're only ever going to be using a string array and you don't want to use any more libraries:
public static String toJSON(String[] array)
{
String json = "[\"";
for (String s : array)
{
json += s + "\",\"";
}
return json.substring(0, json.length() - 2) + "]";
}
Depending on what Javascript framework you're using on your client-side, your JSON will be available as the xmlHttpRequestObject.responseText. AngularJS stores it in the $http.get().success method's first data parameter. jQuery stores it in the $.ajax({success}) method's first data parameter. Angular and jQuery automatically validate and eval it to an [object Object] for you, but xmlHttpRequestObject.responseText doesn't.
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'}.