I have a json from my server which is -
{"canApprove": true,"hasDisplayed": false}
I can parse the json like this -
var msg = JSON.parse('{"canApprove": true,"hasDisplayed": false}');
alert(msg.canApprove); //shows true.
At my ajax response function I caught the same json mentioned earlier by a method parameter jsonObject -
//response function
function(jsonObject){
//here jsonObject contains the same json - {"canApprove":true,"hasDisplayed": false}
//But without the surrounding single quote
//I have confirmed about this by seeing my server side log.
var msg = JSON.parse(jsonObject); // this gives the error
}
But now I got the following error -
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of
the JSON data
Can anyone tell me why I am getting the error?
Your JsonObject seems is a Json Object. The reasons why you can't parse Json from a String:
the String is surround by " ". and use \" escape inside. Here is an example:
"{\"name\":\"alan\",\"age\":34}"
when you try to parse above string by JSON.parse(), still return the a string:{"name":"alan","age":34}, and \" is replace by ". But use the JSON.parse() function again, it will return the object you want. So in this case,you can do this:
JSON.parse(JSON.parse("{\"name\":\"alan\",\"age\":34}" ))
Your string use ' instead of " . example:
{'name':'alan','age':34}
if you try to parse above string by JSON.parse(), may cause error
I dont think you should call JSON.parse(jsonObject) if the server is sending valid JSON as it will be parsed automatically when it retrieves the response. I believe that if You set the Content-type: application/json header it will be parsed automatically.
Try using jsonObject as if it was already parsed, something like:
console.log(jsonObject.canApprove);
Without calling JSON.parse before.
This answer might help someone who's storing JSON as a string in SQL databse.
I was storing the value of following
JSON.stringify({hi:hello})
in MySQL. The JSON stored in SQL was {"hi":"hello"}
Problem was when I read this value from db and fed it to JSON.parse() it gave me error.
I tried wrapping it in quotes but didn't work.
Finally following worked
JSON.parse(JSON.stringify(jsonFromDb))
This worked and JSON was parsed correctly.
I know the storing mechanisim might not be appropriate however those were client needs.
Its already an object, no need to parse it. Simply try
alert(jsonObject.canApprove)
in your response function.
Json.parse is expecting a string.
Your jsonObject seems already parsed, you need to test if this is the case.
function(jsonObject){
var msg = (typeof jsonObject == "object" ? jsonObject : JSON.parse(jsonObject));
}
It's also possible that your call back is empty, it's generates the same error if you try to parse an empty string. So test the call back value.
function(jsonObject){
if(jsonObject) {
var msg = (typeof jsonObject == "object" ? jsonObject : JSON.parse(jsonObject));
}
}
var text = '{"canApprove": true,"hasDisplayed": false}';
var parsedJSON = JSON.parse(text);
alert(parsedJSON.canApprove);
This works. It is possible that you use " instead of ' while creating a String.
Here is an example of how to make an ajax call and parse the result:
var query = {
sUserIds: JSON.stringify(userIds),
};
$.ajax({
type: "POST",
url: your-url,
data: JSON.stringify(query),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (response) {
var your_object = JSON.parse(response.d);
},
failure: function (msg) {
alert(msg);
},
error: function (a, b, c) {
}
});
I faced similar problem and now it's solved. I'm using ASP.Net MVC to send value to .js file. The problem was that I was returning JsonResult from the Action method, because of this JSON.parse was failing in .js file. I changed the return type of Action method to string, now JSON.parse is working fine.
As someone mentioned up there, this actually fixes the problem. What I learnt from this is that may be how PHP encodes a json object is not familiar to JavaScript.
var receivedData = data.toString()
receivedData = JSON.parse(receivedData)
console.log(receivedData.canApprove)
This will work.
Related
I have this following code.
success: function(data) {
console.log(data) //everything
console.log(data['quote']); //undefined
var JSONObject = JSON.parse(data); //why parse again?
var quote =JSONObject['quote']
console.log(data['quote']); //returns quote
}
why do I need to parse the JSON object again even though the return from api call is already a JSON Object?
It seems the data returned from server is JSON string instead JSON object. If the data is string, you need to parse that string to javascript object.
I know this is usually an issue of unbalanced parens and curly braces, however after carefully sifting through my syntax, I have, to the best of my ability, confirmed the correct parity of each of these scope delimiters and have no other recourse except to allow my fellow S.O. pundits to take a gander at the following:
$.ajax({
url: "/application/get_programs_for_center",
type: "POST",
data: formdata,
success: function(response){
var options = $("#school_application_program_name");
var result = JSON.parse(response);
console.log(result);
$.each(result, function() {
options.append($("<option />").val(this.id).text(this.name));
});
}
});
N.B. the error is being thrown in the middle of the line var result = JSON.parse(response); specifically immediately after JSON.
The problem you have is that what you parse isn't JSON.
And the reason it's not JSON, is that the response argument you receive is already parsed from JSON by jQuery. Don't parse it again.
If you parse JSONArray, jQuery will not parse it into Object directly, you have to use JSON.parse(response)
However, if you parse a JSONObject, it will be identified and parse into Object automatically
So keep it in mind, that will help you!
"This" is what I retrieve from a server:
after an ajax call in jQuery:
$.ajax({
type: "POST",
url: URL + "/webservices/WS.asmx/MyFunction",
data: JSON.stringify({ "ID": ID }),
contentType: 'application/json; charset=utf-8',
success: function (json) {
},
error: function (jqxhr, text, error) {
}
});
and I want to iterate the items inside data (which is an array). Tried with:
for (i in json.data) {
var feed = json.data[i];
console.log(feed.message);
}
but it prints nothing. Where am I wrong?
If what you've shown is really what you're getting in your success method, you have an object with a property, d, which contains a JSON string. You can parse it like this:
success: function(response) {
var data = $.parseJSON(response.d).data;
// use the data, which is an array
}
From your comment below:
But why I need to use $.parseJSON? Can't just manage it with the request? dataType for example, but still not works.
You don't need dataType, it would appear the server is returning a correct MIME type and so jQuery is already handling the first level of parsing (deserialization) correctly.
Whatever is sending you the data appears to be sending it double-encoded: First it encodes the array, then creates an object and assigns the array to it as a data property, serializes that object to JSON, then puts that string on a d property of another object, and serializes that. So although jQuery is automatically handling the first parsing (deserializing) step for you, it doesn't know about the need for the second one. I suspect you can fix this at the server level; you might want to post a separate question asking how to do that.
From your further comment:
It retuns from a .NET webservice method. I download the JSON from Facebook, after a call. And I store it inside a json variable. Then I just return it as string. I think webservice serialize that already serialized json, right?
Ah, so that's what's going wrong. You have three options:
Keep doing what you're doing and do the explicit $.parseJSON call above.
Do whatever you need to do in your web method to tell it that you're going to send back raw JSON and it shouldn't encode it; in that case, jQuery will have already parsed it for you by the time you receive it in success and you can drop the parseJSON call.
Parse the string you get from Facebook, then put the resulting array in the structure that your web method returns. Then (again) jQuery will parse it for you and you can use response.d.data directly without further parsing.
As #T.J.Crowder has pointed out your problem is related to the way you serialize your data on your backend, which is not a good practice to send the json as a string, in a real json object.
you should do it like:
success: function (json) {
var jsonObject = JSON.parse(json.d);
//then iterate through it
for(var i=0;i<jsonObject.data.length;i++){
var feed = jsonObject.data[i];
console.log(feed);
}
},
The point is using for(var key in jsonObject.data), is not safe in JavaScript, because additional prototype properties would show up in your keys.
Try using
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(i+" "+feed);
}
where
i = Key &
feed = value
I assume json is an object not string and already converted to json object. Also used json.d.data not json.data
use var in for loop and print feed not feed.message:
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(feed);
}
because I can not see {feed:{message:''}} there
I have a php returning some json in response to a POST request made via an ajax function.
In my php function I format the data like this:
//json return
$return["answers"] = json_encode($result);
echo json_encode($return);
This returns the following string:
answers: "[{"aa":"Purple","0":"Purple","ab":"Blue","1":"Blue","ac":"Red","2":"Red","ad":"Yellow","3":"Yellow"}]"
And this is where I am trying to catch it to use the data:
$.ajax({
type: "POST",
url: "http://ldsmatch.com/pieces/functions/question.functions.php",
dataType : 'JSON',
data: dataString,
success: function(data) {
alert(data.answers[0]["aa"]);
}
});
I've been trying to just alert the data so I can visualize it before setting up the vars I need, but am having some trouble formatting it correctly so it is usable.
If I alert data.answers[0] then it just shows me the first character in the string, which is a bracket [ and if i subsequently change the number it will go through each character in the returned string.
I have tried other variations, such as:
data.answers[0]["aa"] (this returns 'undefined' in the alert)
data.answers["aa"] (this returns 'undefined' in the alert)
data.answers[0] (this returns the first character of the string)
I feel like I'm close, but missing something. Any guidance appreciated.
edit:
thanks for all the suggestions. I removed the second json_encode and was able to parse with data.answers[0].aa
success: function(data) {
var json = $.parseJSON(data);
alert(json.answers[0]["aa"]);
}
Use parseJson like this
var json = $.parseJSON(data);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
What if you remove double-encoding on PHP side? You've got an object with JSON string instead of object with first property being object itself, or you may explicitly decode "answers" property on client side as it was suggested above.
I am receiving following data from server
"[{\"role_id\":\"1\",\"name\":\"administrator\",\"created_by_user_id\":\"2\",\"time_created_on\":null,\"is_user_based\":\"0\"},{\"role_id\":\"2\",\"name\":\"manager\",\"created_by_user_id\":null,\"time_created_on\":null,\"is_user_based\":\"0\"}]"
which is simply an array of two objects . Even after setting 'dataType' to json I am not receiving native javascript array inside my success callback function but if I use
$.ajaxSetup({
url:'/public/admin/role/list',
dataType:'json'
});
$.ajax({
success:function(data) {
alert(data[0].name); // alert box pop up as 'undefined '
var data = $.parseJSON(data);
alert(data[0].name) ; //works
}
});
Don't escape the ". They're required for JSON parsing.
[{"role_id":"1","name":"administrator","created_by_user_id":"2","time_created_on":null,"is_user_based":"0"},{"role_id":"2","name":"manager","created_by_user_id":null,"time_created_on":null,"is_user_based":"0"}]
You have a trailing comma when setting dataType in your ajaxSetup method:
dataType:'json',
^
Also I hope those \ in the JSON you have shown here are not part of the actual response from the server. The response should look like this:
[{"role_id":"1","name":"administrator","created_by_user_id":"2","time_created_on":null,"is_user_based":"0"},{"role_id":"2","name":"manager","created_by_user_id":null,"time_created_on":null,"is_user_based":"0"}]