Why does 'getJson' not work? [closed]

1

My select-menu.json file looks like this:

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

And I'm trying to get it this way:

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

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

    
asked by anonymous 28.08.2015 / 22:47

3 answers

2

Add a error handler to catch errors:

In this example, we use the 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 may see the error that is quite obvious.

The content of the select-menu.json file has an invalid json format.

Correct in the following format:

[
{
    "value": 1,
    "descricao": 1
},
{
    "value": 2,
    "descricao": 2
},
{
    "value": 3,
    "descricao": 3
}
]
    
28.08.2015 / 23:56
2

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

  • value: "1", should be written as "value": "1",
  • JSON is a format, does not exist ;
  • what you wrote is array , so it should be embedded in [] or [ { "value":"1","descricao":"2"}, ... ]
  • use an Online Parser to see if the syntax is correct, eg link

    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 bit more information about the format, the variables have to be delimited by double quote " , only the values is not ...

    "value": "3"
    

    causes value to have the value of a string with content 3

    "value": 3
    

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

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

        
    29.08.2015 / 14:09
    1

    To use "." you must have a json object: then look at the documentation for 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]
        })
    });
    
        
    28.08.2015 / 22:52