Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getJSON only returning [object Object],[object Object]

I am testing out some code and I have created a json file with the data.

The problem is that I'm getting "[object Object],[object Object]" in the alert. No data.

What I'm I doing wrong?

Here is the code:

<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<script>

    $(document).ready(function() {
        $.getJSON("appData.json",function(results){alert(results);});
    });

</script>

</head>
<body>

</body>
</html>

and here is the content of appData.json

[{"foo":"bar"},{"foo2":"blablabla"}]

Also, The index.html file and the json file are both on my desktop and I am running it from there.

like image 894
Satch3000 Avatar asked Sep 22 '26 23:09

Satch3000


2 Answers

please try like this:

$.getJSON("appData.json", function(results) {
        $.each(results, function(index) {
            alert(results[index].foo);
        });
    });
like image 160
Pradeeshnarayan Avatar answered Sep 25 '26 13:09

Pradeeshnarayan


Well, you're getting an array of objects, and arrays and objects are data.

  //          v----first Object in the outer Array
alert(results[0].foo);
  //              ^----foo property of the first Object

It's just that an alert shows the default toString() values of the objects.

When you use $.getJSON, jQuery parsed the JSON text into JavaScript objects automatically. If you wanted the raw JSON, then make a $.get request instead.


If you want to iterate the Array, use a for loop, or one of the iteration methods from jQuery or the native API.

like image 30
user1106925 Avatar answered Sep 25 '26 13:09

user1106925