Understanding the JSON file

9

I have code similar to this in JSFiddle . On my WAMP server at home I tried to work with JSON (JSFiddle does not contain the JSON file to test).

In a question I asked about how to insert data into a database with jQuery answered me that it would be a good option to store the data in JSON files. The answer author showed me what the syntax of the JSON file would look like. You said you could do the following:

[
   { titulo: 'ET', ano: 1982 },
   { titulo: 'Indiana Jones', ano: 1981 }
]

In my tests with this jsfiddle code worked well when the JSON file was in the format:

{
    "Titulo": "Até que a sorte nos separe",
    "segundo": "segundo valor",
    "terceiro": "terceiro valor, o ultimo valor não precisa de virgula"
}

But when I put in the format that the author of the answer to my first question showed, clicking on the "Click me to list" link does not fire anything.

I would like to know the difference between the two syntaxes, because I want to make a small website with a small database with information about the movies I've watched and the ones I'm still going to see. A link on where to get this information from how to mount a JSON file and how to access those values would be a good one.

I use the $.ajax() method to retrieve my JSON that is inside a * .json file as per code:

$.ajax({
    url: 'js/vendor/testedb.json',
    dataType: 'json',
    success: function(data) {


        var item = [];

        $.each(data, function(key,val) {
            item.push('<li id="' + key + '">' + val + '</li>');
        });

        $('<ul/>',{
            'class': 'myclass',
            html: item.join('')
        }).appendTo('body');


    },
    statusCode: {
        404: function() {
            alert("some problem");
        }
    },

});
    
asked by anonymous 30.01.2014 / 19:14

7 answers

4

As I was the one who suggested JSON and created the confusion, I will explain: the JSON that I posted in the other answer was invalid (I have already corrected), because in JSON the keys must be enclosed in double quotation marks, as well as values of type < in> String .

So the JSON file could contain exactly what Gabriel Ribeiro suggested :

[
    {
        "Titulo": "Até que a sorte nos separe",
        "duracao": "120 min"
    },
    {
        "Titulo": "Matrix",
        "duracao": "140 min"
    }
]

(I removed the accented characters to avoid problems, although they are valid.)

A jQuery example to get and use this data via ajax would be:

$.getJSON(url_do_json, function(dados) {
    for(var i=0; i<dados.length; i++) {
        $(document.body).append('<div>' + dados[i].titulo + ', ' + dados[i].duracao + '</div>');
    }
});
    
30.01.2014 / 20:17
6

A great link to JSON syntax interpretation is this: link any JSON, that this site interpret OK without errors, you can use in your code, however on your JSON:

[
   { titulo: 'ET', ano: 1982 },
   { titulo: 'Indiana Jones', ano: 1981 }
]

This above JSON is incorrect, you see that putting it in the json parser online does not cause errors.

{
    "Titulo": "Até que a sorte nos separe",
    "segundo": "segundo valor",
    "terceiro": "terceiro valor, o ultimo valor não precisa de virgula"
}

This JSON above, is correct, it will not fault, but you should not use it because you need to denote an object to access objeto.propriedade as I am doing in the Array below:

Here you have a "Movie" Array of Objects where you can use it to iterate your movies.

ObjetoJSON = {

    "filme":[
        {
            "titulo":"Titulo do seu filme",
            "segundo":"segundo valor",
            "terceiro":"terceiro valor, o ultimo valor não precisa de virgula"
        },
        {
            "titulo":"Titulo do seu filme 2",
            "segundo":"segundo valor 2",
            "terceiro":"terceiro valor, o ultimo valor não precisa de virgula 2"
        },
        {
            "titulo":"Titulo do seu filme 3",
            "segundo":"segundo valor 3",
            "terceiro":"terceiro valor, o ultimo valor não precisa de virgula 3"
        }
    ]

};
ObjetoJSON.filme[0] //seu objeto json do seu filme [0]
ObjetoJSON.filme[0].titulo //seu valor do titulo do filme [0]
ObjetoJSON.filme[0].segundo //o "segundo" valor do filme [0]
ObjetoJSON.filme[0].terceiro// o "terceiro" valor do filme [0]

EDIT:

To use JSON within a file of the * .json extension retrieved from an AJAX Request you should do the following:

Use the following JSON code (this time without definition by variable) in your * .json file:

{
  "filme":[
        {
            "titulo":"Titulo do seu filme",
            "segundo":"segundo valor",
            "terceiro":"terceiro valor, o ultimo valor não precisa de virgula"
        },
        {
            "titulo":"Titulo do seu filme 2",
            "segundo":"segundo valor 2",
            "terceiro":"terceiro valor, o ultimo valor não precisa de virgula 2"
        },
        {
            "titulo":"Titulo do seu filme 3",
            "segundo":"segundo valor 3",
            "terceiro":"terceiro valor, o ultimo valor não precisa de virgula 3"
        }
    ]
}

And use this javascript code so that you understand JSON, and then tailor it in the way you use it:

$.ajax({
    url: 'js/vendor/testedb.json',
    dataType: 'json',
    success: function(data) {
      console.log('Titulo: ' + data.filme[0].titulo + ' Segundo: ' + data.filme[0].segundo);
    },
    statusCode: {
        404: function() {
            alert("some problem");
        }
    },

});
    
30.01.2014 / 19:22
3
{
    "nome": "Kadu",
    "idade": "25"
}

This is an Object that stores a name and an age.

{
    "pessoas": [
        { "nome": "José", "idade": "80" },
        { "nome": "Maria", "idade": "60"}
    ]
}

This is an array of people. Each time you have a collection or dataset, you can store them in an array and iterate through this array using a looping structure.

    
30.01.2014 / 19:28
3

In your first example, you are creating a vector with two objects. The correct syntax would be the second, and to create more objects you have to do the following:

[
    {
        "Titulo": "Até que a sorte nos separe",
        "duração": "120 min"
    },
    {
        "Titulo": "Matrix",
        "duração": "140 min"
    }
]
    
30.01.2014 / 19:31
2

It would be cool if you read the JSON documentation, follow the links:

MDN: link

JSON: link

I see a lot of people mistaking the JSON format with Object Literal, see an example:

JSON:

{"nome":"Fabio", "sobrenome":"Silva", "idade":35}

Object Literal:

{nome:"Fabio", sobrenome:"Silva", idade:35}

I can not put more than two links yet, but there's plenty of stuff on the net that can shed more light on how you should work with JSON, and the difference that exists with Object Literal.

I hope I have helped!

    
30.01.2014 / 20:18
1

The first example is a json array with 2 objects, each object has a title and a year.

The second example is a simple json object with 3 properties (3 key-value pairs).

I recommend a format similar to the first example (an array of objects) to represent a collection of movies.

["titulo 1", "titulo 2"] 
    
30.01.2014 / 19:22
1

Another site I like to access for JSON editing is this:

link

It's very simple to use.

    
30.01.2014 / 20:42