JQuery parse JSON - javascript

I'm fairly new to JQuery. The code below works and I can see the correct JSON response in Firebug. But I couldn't find a way how to get and parse it in the code. Alert window only shows
"[object Object]" but not any json text.
<script>
$.ajaxSetup({ cache: false });
var _token;
function make_token_auth(user, token) {
var tok = user + ':' + token;
return "Token " + tok;
}
$.ajax
({
type: "GET",
url: "url",
dataType: 'json',
beforeSend: function (xhr){
xhr.setRequestHeader('Auth', make_token_auth('userid', 'token'));
},
success: function (data){
alert(data);
}
});
</script>

The fact you precised
dataType: 'json',
tells jQuery to parse the received answer and give it as a javascript object to your success callback.
So what you have here is fine and what is alerted is correct (this is an object, so
alert simply prints the result of data.toString()).
Use console.log to see what it is exactly :
success: function (data){
console.log(data);
}
and open the developer tools in Chrome or the console in Firebug to browse the properties of the object.

don't use alert() for debugging -- it's often unhelpful (as in this case), and also has serious issues when used with asyncronous code (ie anything Ajax) because it interrupts the program flow.
You would be much better off using the browser's console.log() or console.dir() functions, and seeing the object displayed in the console. It is much more functional, and doesn't interrupt the flow of the program.
So instead of alert(myjsonvar) use console.log(myjsonvar).

You can get the json string by using JSON.stringify
var jsonstr = JSON.stringify(data);
alert(jsonstr);

The alert function expects you to pass in a string or number.
Try doing something like this:
for(x in data) {
alert(x + ': ' + data[x]);
}
Update in response to comments: You can use alert in development or production to see string and number values in the object returned by the server-side code.
However, carefully rereading your question, it looks like what you really want to see is the actual JSON text. Looking at #dystroy's answer above, I think that if you remove the dataType: 'json' from your $.ajax invokation, jQuery will treat the response as plain text instead of automatically converting it to an Object. In this case, you can see the text by passing it to the alert function.

Try using
data = JSON.parse(data)
Then do whatever you want with the data.
Source: JSON.parse() (MDN)

Related

Intercept and modify JSON string before jQuery.getJSON() does its thing

I use jQuery's getJSON call to rerieve the content from a file called my.json.
Now sometimes the JSON file contains a certain character, that would invalidate the syntax. Unfortunately, it is not in my power to change that.
I thought it would be easy to use the success thing to intercept the JSON string and dix it, before $.getJSON() reads it and fails because the syntax is invalid. Obviously, it's not as easy, as I thought.
I would appreciate, if someone could help me out fixing below code.
$.ajaxSetup({
beforeSend: function(xhr){
if (xhr.overrideMimeType) {
xhr.overrideMimeType("application/json");
}},
cache: false
});
$.getJSON("my.json", function(data){
// Do something with the JSON
console.log("JSON object: " + data);
}).success(function(data, textStatus, jqXHR) {
// Intercept JSON string and modify it.
var fixed_json = fix_json(jqXHR.responseText);
jqXHR.responseText = fixed_json; // Obviously not as simple as I thought.
});
You can use the success callback of $.ajax() to do the required check on the returned data. It would require you to set the dataType to text though, so that jQuery doesn't try and automatically parse it for you. Try this:
$.ajax({
url: "my.json",
dataType: 'text',
success: function(data) {
var obj;
try {
obj = JSON.parse(data);
}
catch(e) {
obj = fix_json(data);
}
// work with the object here...
})
});
Example fiddle
Depending on the work that fix_json does, and assuming that it always returns an object, you could call that directly and remove the try/catch.

Ajax request, fetch JS array and make it available

I'm trying to fetch a JS array created by a PHP file and re-use the JS array in a JS script in the page. I have tried many different solutions found on this site but none seems to work but I don't know what the issue is with my script.
I have a PHP file that echoes the following:
[["content11", "content12", "content13", "content14","content15"],
["content21", "content22", "content23", "content24","content25"]]
I'm using a simple Ajax get to retrieve the data:
$.ajax({
type: "GET",
url: myUrlToPhpFile,
dataType: "html",
success : function(data)
{
result = data;
alert (result);
}
});
The alert displays the expected output from the PHP file but if I now try to access the array like result[0], it outputs "[" which is the first character. It looks like JS sees the output as a string rather than an array.
Is there something I should do to make JS understand it's a JS array?
I have seen many solution with JSON arrays but before going into this direction, I'd like to check if there are simple solutions with JS arrays (this would prevent me from rewriting too much code)
Thanks
Laurent
In you php file you need check that your arrays echos with json_encode.
echo json_encode($arr);
And in your javascript file:
$.ajax({
type: "GET",
url: myUrlToPhpFile,
dataType: "html", // json
success : function(data)
{
var res = JSON.parse(html);
alert(html); // show raw data
alert(res); // show parsed JSON
}
});
You can use JSON.parse to format the string back into an array.
JSON.parse(result)[0]
or
var result = JSON.parse(result);
result[0];
#Rho's answer should work fine, but it appears that you're using jQuery for your AJAX call, which gives you a shortcut; you can use $.getJSON instead of $.ajax, and it will read the data as JSON and provide you with the array immediately.
$.getJSON(myUrlToPhpFile, function(result) { ... });
This is really just a short way of writing what you already have, but with a dataType of json instead of html, so you could even do it that way if you prefer. This is all assuming that you're using jQuery of course, but your code was following their API so it seems a good bet that you're either using jQuery or something compatible.

Parsing JSON returned via an AJAX POST formating issue

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.

JSON returned from ASP.NET not usable in JS

I'm returning a DataSet converted to JSON via a jQuery AJAX call, all is well! The request I receive back is:
{"Table":[[2,"BlackBerry Tour","2013-09-10","2013-09-13","Project"],null]}
Looks valid to me, also ran it through JSLint validator, again, all is well! Now, whenever I try to access any of this data, I simply receive undefined from the following:
var dataObject = data.d //data.d is the response from the server and what is logged above
console.log(dataObject.Table) //undefined
console.log(dataObject["Table"]) //undefined
Now, if I run JSON.parse(dataObject), I can then access it alright. This is a problem right now however, since the site this will reside on sticks IE into IE7 mode, and JSON is always undefined according to IE (I know, IE7, it's out of my hands tho).
So my question is why can I not use the returned JSON as is? why must I run it through JSON.parse before using it? More info is available on request (AJAX call, DataSet converter, etc)
AJAX Call, per request:
$.ajax({
type: "POST",
url: "DBManager.asmx/GetAdminList",
contentType: 'application/json',
data: '{"strEmail": "' + strFilter + '" }',
dataType: "json",
success: function (data) {
console.log(data.d); //valid JSON response.
}
});
If you returning back a string you have to somehow parse it into an object. E.g.
var data = '{"Table":[[2,"BlackBerry Tour","2013-09-10","2013-09-13","Project"],null]}';
var dataJ
eval('dataJ = ' + data )
alert(dataJ.Table)
http://jsfiddle.net/uvvAm/
If you're using jQuery you can use
var dataJ = $.parseJSON(data);
This is preferable, since eval is open to all kinds of attacks.
var dataObject = eval('(' + data + ')');
alert(dataObject.Table);
Try this thing may help you.

jQuery ajax method with dataType 'json' incorrectly parsing json data

I'm having some inexplicable behaviour using jQuery 1.4.2, and I'm beginning to think that it might be a safari problem, not a jQuery one. Let me explain.
I began simply enough by using .getJSON like this:
$.getJSON("/challenge/results", form_data, function(data){
//I know console.log is bad news, just a simplification.
console.log('data', data);
}
And the log gave me something along the lines of
>locations: Array (1)
While I was expecting an array of size 2. So I had a look at the json in the response:
{"locations":
[{"customer_id":2,"editable":true,"id":971,"latitude":43.659208,"longitude":-79.407501,"max_zoom":25,"min_zoom":9,"name":"test"},
{"customer_id":3,"editable":true,"id":974,"latitude":36.746944,"longitude":-107.970899,"max_zoom":25,"min_zoom":9,"name":"test2"}]}
I've simplified this considerably for the sake of clarity, but as far as I can tell, the json received is perfectly valid (generated programmatically through rails). [Update: JSONLint confirms this hypothesis.]
I was surprised by this, so I converted my request to a $.ajax request to see if there was some subtle difference between them (since then, looking in the source of jQuery I see that $.getJSON simply calls $.ajax).
$.ajax({
url:"/challenge/results",
dataType: 'json',
data: form_data,
cache:false,
success: function(data, textStatus){
console.log("data!", data, textStatus);
});
But alas! The same response:
locations: Array (1) success
At this point, I must admit - I was getting a bit silly, so I thought I would try something completely bound to fail:
$.ajax({
url:"/challenge/results",
dataType: 'text',
data: form_data,
cache:false,
success: function(data, textStatus){
console.log("Parsed:!", $.parseJSON(data), textStatus);
});
Much to my surprise my console read:
locations: Array (2) success
I was stumped. At this point I dug in my heels and took a long hard look at the jQuery source (1.4.2). I suppose unsurprisingly, the ajax function seems not to handle the json parsing itself (although, I must admit, I can't be sure).
I'm totally at a loss for why this could be happening - any help is appreciated.
Perhaps I missed something, but I notice that your JSON is an object that has a single property ("locations") with an array as it's value. Have you tried:
$.getJSON("/challenge/results", form_data, function(data){
//I know console.log is bad news, just a simplification.
console.log('data', data.locations);
}
try this:
// Enables for all serialization
jQuery.ajaxSettings.traditional = true;
// Enables for a single serialization
jQuery.param( stuff, true );
// Enables for a single Ajax requeset
$.ajax({ data: stuff, traditional: true });
hey,your problem seems like to be have something to do with the nested param serialization.just as what the jQuery 1.4 release note say:
Query 1.4 adds support for nested param serialization in jQuery.param, using the approach popularized by PHP, and supported by Ruby on Rails. For instance, {foo: ["bar", "baz"]} will be serialized as “foo[]=bar&foo[]=baz”.
In jQuery 1.3, {foo: ["bar", "baz"]} was serialized as “foo=bar&foo=baz”. However, there was no way to encode a single-element Array using this approach. If you need the old behavior, you can turn it back on by setting the traditional Ajax setting (globally via jQuery.ajaxSettings.traditional or on a case-by-case basis via the traditional flag).
The Webkit inspector's debugger should be used instead of console logging, which can show the object in a future state. This was the cause of this problem as the list was being trimmed in code after the console.log line, which resulted in the unexpected behaviour.

Categories

Resources