Understanding the JSON file

Asked

Viewed 16,282 times

9

I have a code similar to this on Jsfiddle. On my home WAMP server I did to try working 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 I was told that it would be a good option to store the data in JSON files. The author of the reply showed me what the syntax of the JSON file would look like. He said he 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 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 it in the format that the author of the answer to my first question showed, the click on the link "Click me to list" does not trigger 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 already watched and the ones I’m still going to see. A link on where to get this information on how to build a JSON file and how to access these values would be a good one.

I use the method $.ajax() to rescue my JSON that is inside a file *.json by 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");
        }
    },

});
  • Clarifying your question about posting JSON here, put your question JSON, if you need help editing, we do it for you. Put as much as you can into the question unless it is something very big (which would probably be wrong to help the problem).

  • I edited my answer, like you asked, @Pedro Gelli

  • I added a new solution adapted to your @Pedrogelli method, but I advise you to add the code of $.ajax() here in the question as it is extremely important.

7 answers

6

A great link to JSON syntax interpretation is this: http://json.parser.online.fr/ any JSON, which this site interprets OK without errors, you can use in your code, but about your JSON:

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

This JSON above is incorrect, see that if you put it in json parser online it accuses 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 accuse errors, but you should not use it because you need to denote an object to access objeto.propriedade as I am doing in the Array just below:

Here you have an Array of "Movie" 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 *.json file rescued from an AJAX Request you must do the following:

Use the following JSON code (this time without variable definition) 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 to make you understand JSON, and then adapt it 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");
        }
    },

});
  • Could I create more than one json object in the same json file? One for each movie?

  • Yes, I’ll add an example

  • @dcastro I was using the example that the OP quoted, but now there is a beautiful example below.

  • Does the "Objetojson" object definition lie within the JSON file? And the "Objetojson.movie[0]" I put in a.log console when clicking but says undefined. I put in the JSON file all the definition of "Objetojson".

  • Why do you need a "JSON File"? Run my entire block of code in javascript, you will see that javascript will create the "Objetojson" variable and define it as a JSON, you can change this name, it is just a variable, remember.

  • I understand what you want to do, @Pedrogelli. But you need to rescue this same JSON file from server ? it will be dynamic? if yes, let me know because I have to edit my answer. If not, you can just declare JSON in Javascript and access exactly how I showed it.

  • 1

    @Pauloroberto I suggested using a JSON on the server because its goal is to learn (see commenting in the other question), and with that he would already learn how the access to data works from the customer, in real life.

  • 1

    @bfavaretto that generated a big confusion in my mind with his question, but that’s okay, right. At least I could understand and last I posted what he wanted.

Show 3 more comments

4


As I was the one who suggested the JSON and created the confusion, I will explain myself: the JSON I posted in the other answer was invalid (already corrected), because in JSON the keys need to be in double quotes, as well as values of type String.

Therefore, 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.)

An example in jQuery 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>');
    }
});
  • Does this replace the code used in $.ajax()? I say delete all $.ajax() and use $.getJSON()?

  • 1

    This is a shortcut to $.ajax with certain options already set to catch json. Whatever you use.

  • Great! Thanks now I can list the properties of these objects. Can I ask now how I insert a new JSON (Movie) object? I set variables with prompt when the user clicks the link. But how do I insert the value of these variables into a new JSON object? I took a look at jquery.com but couldn’t find anything to help me. Is it using jQuery.parseJSON? Can you give me a hand? To lost. http://jsfiddle.net/pedrogelli/LAapR/1/

  • @Pedrogelli If you want salvage this json, then you’ll need to mess with server-side scripting (in php, js with Node, c# Asp.net, python, whatever you want). But being only in js, to insert another film on the screen, I gave a little help there in your fiddle: http://jsfiddle.net/LAapR/2/. If you have more questions, I suggest posting a new question, because we are already escaping the scope of the original.

  • That’s exactly what I want, to save this json. I’ve been taking a look at Node.js and really liked it, I really want to test with it. So now I must create a new question about how to save data in the server json, right?

  • That’s it, @Pedro. But I’ll tell you this: it would be nice for you to have some server-side programming domain before you try this.

  • Since I don’t have that knowledge, could you point me to some link so I can start studying? @bfavaretto

  • @Pedrogelli Now you got me, I don’t know no...

Show 3 more comments

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. Every time you have a collection or dataset, you can store them in an array and you can iterate through that array using a loop structure.

  • Thanks, so the way the person answered me before this topic this wrong writing right?

  • All that was missing was the "{}"

  • I believe that it was not only @Novok, because in javascript the JSON cited by him, in the first example, would never run, because Javascript would understand titulo and ano as an undeclared variable: undefined variable.

  • 1

    Whoa, whoa, that’s right!

  • In fact the json I had suggested was invalid due to missing quotation marks, but the object on the outside is not necessary. Json may simply be an array.

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 as follows:

[
    {
        "Titulo": "Até que a sorte nos separe",
        "duração": "120 min"
    },
    {
        "Titulo": "Matrix",
        "duração": "140 min"
    }
]
  • 1

    The root of a json document must be either an object, or an array. The root of that format is invalid because it has two objects

  • That’s correct, I summed up the answer too.

  • @dcastro Are you sure? The JSON specification doesn’t mention it. http:/jsonlint.com says it’s valid. JSON.parse also accepts an array.

  • @bfavaretto, I think he was correcting me the way I posted before, in case without the brackets []. []s

  • @Gabrielribeiro Ah, I read it wrong, I thought he was saying that the root had to be an object and not an array.

2

Guy would be nice also you give a read on the JSON documentation, follow the links:

MDN: https://developer.mozilla.org/en/docs/JSON

JSON: http://www.json.org/

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

JSON:

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

Object Literal:

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

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

I hope I’ve helped!

  • I agree, javascript understands any word that is not reserved as a variable. That in most cases will be undefined using a JSON this way.

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 pairs - value).

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

["titulo 1", "titulo 2"] 
  • But then why doesn’t it work in my code? I put it in Json Parser Online and actually error.

  • The parser fails because the Keys (title and year) should be in quotation marks "". As I am on the phone I can not help anymore, but search in google "javascript parse json array"

1

Browser other questions tagged

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