Parse JSON from JQuery.ajax success data

JsonJquery

Json Problem Overview


I am having trouble getting the contents of JSON object from a JQery.ajax call. My call:

$('#Search').click(function () {
    var query = $('#query').valueOf();
    $.ajax({
        url: '/Products/Search',
        type: "POST",
        data: query,
        dataType: 'application/json; charset=utf-8',
        success: function (data) {
            alert(data);
            for (var x = 0; x < data.length; x++) {
                content = data[x].Id;
                content += "<br>";
                content += data[x].Name;
                content += "<br>";
                $(content).appendTo("#ProductList");
               // updateListing(data[x]);
            }
        }
    });
});

It seems that the JSON object is being returned correctly because "alert(data)" displays the following

[{"Id": "1", "Name": "Shirt"}, {"Id": "2", "Name":"Pants"}]

but when I try displaying the Id or Name to the page using:

content = data[x].Id;
content += "<br>";
content += data[x].Name;
content += "<br>";

it returns "undefined" to the page. What am I doing wrong?

Thanks for the help.

Json Solutions


Solution 1 - Json

The data is coming back as the string representation of the JSON and you aren't converting it back to a JavaScript object. Set the dataType to just 'json' to have it converted automatically.

Solution 2 - Json

I recommend you use:

var returnedData = JSON.parse(response);

to convert the JSON string (if it is just text) to a JavaScript object.

Solution 3 - Json

It works fine, Ex :

$.ajax({
    url: "http://localhost:11141/Search/BasicSearchContent?ContentTitle=" + "تهران",
    type: 'GET',
    cache: false,
    success: function(result) {
        //  alert(jQuery.dataType);
        if (result) {
            //  var dd = JSON.parse(result);
            alert(result[0].Id)
        }

    },
    error: function() {
        alert("No");
    }
});

Finally, you need to use this statement ...

result[0].Whatever

Solution 4 - Json

One of the way you can ensure that this type of mistake (using string instead of json) doesn't happen is to see what gets printed in the alert. When you do

alert(data)

if data is a string, it will print everything that is contains. However if you print is json object. you will get the following response in the alert

[object Object]

If this the response then you can be sure that you can use this as an object (json in this case).

Thus, you need to convert your string into json first, before using it by doing this:

JSON.parse(data)

Solution 5 - Json

Well... you are about 3/4 of the way there... you already have your JSON as text.

The problem is that you appear to be handling this string as if it was already a JavaScript object with properties relating to the fields that were transmitted.

It isn't... its just a string.

Queries like "content = data[x].Id;" are bound to fail because JavaScript is not finding these properties attached to the string that it is looking at... again, its JUST a string.

You should be able to simply parse the data as JSON through... yup... the parse method of the JSON object.

myResult = JSON.parse(request.responseText);

Now myResult is a javascript object containing the properties that were transmitted through AJAX.

That should allow you to handle it the way you appear to be trying to.

Looks like JSON.parse was added when ECMA5 was added, so anything fairly modern should be able to handle this natively... if you have to handle fossils, you could also try external libraries to handle this, such as jQuery or JSON2.

For the record, this was already answered by Andy E for someone else HERE.

edit - Saw the request for 'official or credible sources', and probably one of the coders that I find the most credible would be John Resig ~ ECMA5 JSON ~ i would have linked to the actual ECMA5 spec regarding native JSON support, but I would rather refer someone to a master like Resig than a dry specification.

Solution 6 - Json

Try the jquery each function to walk through your json object:

$.each(data,function(i,j){
    content ='<span>'+j[i].Id+'<br />'+j[i].Name+'<br /></span>';
    $('#ProductList').append(content);
});

Solution 7 - Json

you can use the jQuery parseJSON method:

var Data = $.parseJSON(response);

Solution 8 - Json

input type Button

<input type="button" Id="update" value="Update">

I've successfully posted a form with AJAX in perl. After posting the form, controller returns a JSON response as below

$(function() {

	$('#Search').click(function() {
		var query = $('#query').val();
		var update = $('#update').val();

		$.ajax({
			type: 'POST',
			url: '/Products/Search/',
			data: {
				'insert': update,
				'query': address,
			},
			success: function(res) {
				$('#ProductList').empty('');
				console.log(res);
				json = JSON.parse(res);
				for (var i in json) {
					var row = $('<tr>');
					row.append($('<td id=' + json[i].Id + '>').html(json[i].Id));
					row.append($('<td id=' + json[i].Name + '>').html(json[i].Name));
					$('</tr>');
					$('#ProductList').append(row);
				}
			},
			error: function() {
				alert("did not work");
				location.reload(true);
			}
		});
	});
});

Solution 9 - Json

From the jQuery API: with the setting of dataType, If none is specified, jQuery will try to infer it with $.parseJSON() based on the MIME type (the MIME type for JSON text is "application/json") of the response (in 1.4 JSON will yield a JavaScript object).

Or you can set the dataType to json to convert it automatically.

Solution 10 - Json

I'm not sure whats going wrong with your set up. Maybe the server is not setting the headers properly. Not sure. As a long shot, you can try this

$.ajax({
	url : url,
    dataType : 'json'
})
.done(function(data, statusText, resObject) {
   var jsonData = resObject.responseJSON
})

Solution 11 - Json

parse and convert it to js object that's it.

success: function(response) {
    var content = "";
    var jsondata = JSON.parse(response);
    for (var x = 0; x < jsonData.length; x++) {
        content += jsondata[x].Id;
        content += "<br>";
        content += jsondata[x].Name;
        content += "<br>";
    }
    $("#ProductList").append(content);
}

Solution 12 - Json

Use dataType: 'json'

In .NET you could also return Json(yourModel) in your action method/API controller.

And parse the returned JSON as follows in the Jquery .ajax:

if you've a complex object: navigate to it directly.

success: function (res) { 
$.each(res.YourObject, function (index, element) {                                
  console.log(element.text);
  console.log(element.value);
   });

 });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionactkatiemaciasView Question on Stackoverflow
Solution 1 - JsonMarcelo CantosView Answer on Stackoverflow
Solution 2 - JsonabobreshovView Answer on Stackoverflow
Solution 3 - JsonAmin SaadatiView Answer on Stackoverflow
Solution 4 - JsonaashView Answer on Stackoverflow
Solution 5 - JsonSteveView Answer on Stackoverflow
Solution 6 - JsonarabeskeView Answer on Stackoverflow
Solution 7 - JsonSuchit kumarView Answer on Stackoverflow
Solution 8 - Jsonkrunal shimpiView Answer on Stackoverflow
Solution 9 - JsonSky YipView Answer on Stackoverflow
Solution 10 - JsonpravinView Answer on Stackoverflow
Solution 11 - Jsonuser9501432View Answer on Stackoverflow
Solution 12 - JsonJey JegathesanView Answer on Stackoverflow