Why doesn’t getJson work?

Asked

Viewed 3,091 times

1

My file select-menu.json is like this:

{
    value: "1",
    descricao: "1"
},
{
    value: "2",
    descricao: "2"
},
{
    value: "3",
    descricao: "3"
};

And I’m trying to get it that way:

$(document).ready(function(){
    $.getJSON( "js/json/select-menu.json", function( data ) {
       alert(data);
    })
});

But it is not alerting the data. I put the project on the server and the path to the file is correct.

  • in place of alert(data); puts console.log(data); and see what returns.

  • nothing returns either.

  • By pressing F12 in the browser you enter the toolbar where you can go in the browser console to check for errors.

  • there is no mistake.

3 answers

2

Add a error handler to capture errors:

In this example, we use the method fail()

$(document).ready(function() {

    var jqxhr = $.getJSON( "js/json/select-menu.json", function(data) {
      console.log( "success", data );
    })
      .fail(function(textStatus, errorThrown) {
        console.log("error " + textStatus, errorThrown);
      })

});

With this, you can see the error that is quite obvious.

The contents of the archive select-menu.json has a format json invalid.

Fix with the following format:

[
{
    "value": 1,
    "descricao": 1
},
{
    "value": 2,
    "descricao": 2
},
{
    "value": 3,
    "descricao": 3
}
]

2

Voce should first know exactly what the "JSON format is"...

  1. value: "1", should be written as "value": "1",
  2. JSON is a format, there is no ;
  3. what you wrote is a array, should be built in [] that is to say [ { "value":"1","descricao":"2"}, ... ]

use an Online Parser to see if the syntax is correct, for example: http://json.parser.online.fr/

the correct text in your file should be written as:

[
  {
    "value": "1",
    "descricao": "1"
  },
  {
    "value": "2",
    "descricao": "2"
  },
  {
    "value": "3",
    "descricao": "3"
  }
]

Just to add a little more information about the format, the variables have to be delimited by double quote ", only the values is that...

"value": "3"

causes the value has the value of a string with content 3

"value": 3

causes the value has the value of a number with content 3, that is, in the case only his example, and imagining that the object has the variable data:

the result of data[0].value + data[1].value will be of 12 and not 3

1

to use " . "you must have a json Object: take a look later at the documentation the difference between json string, and json Object in the jquery library.

you have to use . parseJson(); example:

$(document).ready(function(){
   $.getJSON( "js/json/select-menu.json", function( data ) {

       var obj = jQuery.parseJSON(data);

       alert(obj.value);
       // como você tem uma lista, provavelmente irá usar um index para
       // obj.value[0] ou obj.value[1]
    })
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.