[ajax] Parse JSON response using jQuery

I'm dealing with a JSON Response in one of my applications. I have established a connection using jsonp successfully. But I'm not able to parse my response.

Code:

<script type='text/javascript'>
(function($) {
var url = 'http://cooktv.sndimg.com/webcook/sandbox/perf/topics.json';

$.ajax({
   type: 'GET',
    url: url,
    async: false,
    jsonpCallback: 'callback',
    contentType: "application/json",
    dataType: 'jsonp',
    success: function(json) {
       console.log(json.topics);
       $("#nav").html('<a href="">'+json.topics+"</a>");
    },
    error: function(e) {
       console.log(e.message);
    }
});

})(jQuery);
</script>

Output i'm getting:

[object Object],[object Object],[object Object]

Response Example:

callback({"topics":[{"name":"topic","content":[{"link_text":"link","link_src":"http://www.foodnetwork.com/"},{"link_text":"link","link_src":"http://www.hgtv.com/"},{"link_text":"link","link_src":"http://www.diynetwork.com/"},{"link_text":"link","link_src":"http://www.cookingchanel.com/"},{"link_text":"link","link_src":"http://www.travelchannel.com/"},{"link_text":"link","link_src":"http://www.food.com/"}]},{"name":"topic2","content":[{"link_text":"link","link_src":"http://www.google.com/"},{"link_text":"link","link_src":"http://www.yahoo.com/"},{"link_text":"link","link_src":"http://www.aol.com/"},{"link_text":"link","link_src":"http://www.msn.com/"},{"link_text":"link","link_src":"http://www.facebook.com/"},{"link_text":"link","link_src":"http://www.twitter.com/"}]},{"name":"topic3","content":[{"link_text":"link","link_src":"http://www.a.com/"},{"link_text":"link","link_src":"http://www.b.com/"},{"link_text":"link","link_src":"http://www.c.com/"},{"link_text":"link","link_src":"http://www.d.com/"},{"link_text":"link","link_src":"http://www.e.com/"},{"link_text":"link","link_src":"http://www.f.com/"}]}]});

I want in the form of :

Topic: Link

This question is related to ajax json object jsonp

The answer is


The data returned by the JSON is in json format : which is simply an arrays of values. Thats why you are seeing [object Object],[object Object],[object Object].

You have to iterate through that values to get actuall value. Like the following

jQuery provides $.each() for iterations, so you could also do this:

$.getJSON("url_with_json_here", function(data){
    $.each(data, function (linktext, link) {
        console.log(linktext);
        console.log(link);
    });
});

Now just create an Hyperlink using that info.


I was hanging out on Google, then I found your question and it's very simple to parse JSON response into normal HTML. Just use this little JavaScript code:

<!DOCTYPE html>
<html>
<body>

<h2>Create Object from JSON String</h2>

<p id="demo"></p>

<script>

var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;

</script>

</body>
</html>

Original question was to parse a list of topics, however starting with the original example to have a function return a single value may also useful. To that end, here is an example of (one way) to do that:

<script type='text/javascript'>
    function getSingleValueUsingJQuery() {
      var value = "";
      var url = "rest/endpointName/" + document.getElementById('someJSPFieldName').value;
      jQuery.ajax({
        type: 'GET',
        url: url,
        async: false,
        contentType: "application/json",
        dataType: 'json',
        success: function(json) {
          console.log(json.value);   // needs to match the payload (i.e. json must have {value: "foo"}
          value = json.value;
        },
        error: function(e) {
          console.log("jQuery error message = "+e.message);
        }
      });
      return value;
    }
    </script>
    


jQuery.ajax({
            type: 'GET',
            url: "../struktur2/load.php",
            async: false,
            contentType: "application/json",
            dataType: 'json',
            success: function(json) {
              items = json;
            },
            error: function(e) {
              console.log("jQuery error message = "+e.message);
            }
        });

Try bellow code. This is help your code.

  $("#btnUpdate").on("click", function () {
            //alert("Alert Test");
            var url = 'http://cooktv.sndimg.com/webcook/sandbox/perf/topics.json';
            $.ajax({
                type: "GET",
                url: url,
                data: "{}",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    debugger;

                    $.each(result.callback, function (index, value) {
                        alert(index + ': ' + value.Name);
                    });
                },
                failure: function (result) { alert('Fail'); }
            });
        });

I could not access your url. Bellow error is shows

XMLHttpRequest cannot load http://cooktv.sndimg.com/webcook/sandbox/perf/topics.json. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:19829' is therefore not allowed access. The response had HTTP status code 501.


Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to jsonp

CORS header 'Access-Control-Allow-Origin' missing JSONP call showing "Uncaught SyntaxError: Unexpected token : " jquery.ajax Access-Control-Allow-Origin Parse JSON response using jQuery parsing JSONP $http.jsonp() response in angular.js How can JavaScript save to a local file? Javascript search inside a JSON object IE9 jQuery AJAX with CORS returns "Access is denied" jquery how to use multiple ajax calls one after the end of the other Callback function for JSONP with jQuery AJAX