JSON format file

4

And then everyone's beauty?

I'm half doubt stupid, but I could not find an answer. I've been parsing a few sites and seen that instead of calling a $.AJAX request on the server to populate a dropdown data, for example, they call a link in JSON format.

For example:

meulocal.com.br/cidades.json 

How can I create this file? Is it advantageous to use it this way?

Thanks for the help.

    
asked by anonymous 20.07.2016 / 15:02

1 answer

4

You create a * .json file the way you create a text file. In a * .json it can be declared any type of value that is accepted, such as null , expression of object {} , expression of Array [] , numeric values, String , Boolean and null , so it can not be empty.

Differences:

  • In an object you can only declare property names with quotation marks between them.
  • If you want to escape characters, declare a \ to look like this: \ n (or \ , computed) in front of the character.

In JavaScript, the JSON object includes two methods:

* 'parse': Interpreta uma string como JSON.
* 'stringify': Transforma um objeto em string, no formato de JSON.

Example of interpreting:

var data = JSON.parse('{"version": 0.5}');
alert("Version: " + data.version);

// Exemplo; expandindo o objeto retornado

with(JSON.parse('{"a": "bla\nbla", "b": true, "c": "ey"}'))
    alert("a: " + a), // -> "bla\nbla"
    alert("b: " + b), // -> true
    alert("c: " + c); // -> "ey"

// Exemplo: inline

alert("a: " + JSON.parse('{"a": "inline"}').a) // -> "inline"

Remembering : Some old browsers may not support the JSON object. This is not worrisome, but if you want to detect it, do a condition like this: typeof window.JSON === "object" , or use some existing "polyfill" .

Vantagious? If you want an easy-to-work project, JSON makes it easy to read and manipulate data. The disadvantage compared to the advantage of comma-separated data (% w / w%), which decreases the amount of characters, is insignificant. I would say that it is vantage.

The doubt in your comment is not related to JSON. You can index any string in an object and then index another object. This is normal in languages like Moon, JavaScript, etc.:

var object = {index: {b: true}};
alert(object.index.a); // undefined
alert(object.index.b); // true
alert(object.b); // undefined
    
20.07.2016 / 15:34