What is JSON? What is it for and how does it work?

Asked

Viewed 47,964 times

27

I usually come across this JSON, but I don’t know what it’s for and how it works.

  • 3

    JSON is a notação (a way of writing) objects in Javascript. It can be seen as a "universal" format that is very convenient for exchanging information between applications through various protocols. "Join" is an English verb that has several meanings, related to junction, joint, accumulation etc. The specific meaning depends on the context. Without an objective context, the question becomes too broad.

  • 2

    @Jeffersonalison take a look here about JSON. About join, which is a method for joining elements of an array/stack, have to be more specific about what language you are looking for. Javascript/PHP/etc

6 answers

37


Concept:

JSON, in its theoretical meaning is "Javascript Object Notation", of which nothing else is that the lightest format known to me of data transfer/exchange, it is similar to the XML, and has the same utility, same purpose, but is lighter, the detail is that not necessarily, despite the name, you have to use it with Javascript. Many languages today support JSON, it’s kind of a new, old-known substitute method XML. It is often used to return data from a server using requests AJAX to update data in real time.

Information and Examples:

Many reputable companies and systems today use JSON, such as Google and Yahoo. With it we can store data in a way that works as follows:

We have a simple JSON object, it should contain a denotation (which is highly recommended) or not, for example:

{"ObjetoPai":"valor"}

Now I will show a more complex JSON object with parent and child object.

{
"ObjetoPai":{
    "ObjetoFilho":"valor"
  }
}

We can have an Array of child objects, too:

{

    "ObjetoPai":[
        {
            "ObjetoFilho":"valor"
        },
        {
            "ObjetoFilho":"valor"
        }
    ]

}

JSON can be complex, you can have more than one parent object with children as well, and for types it accepts integer, boolean, and also string values, as you can see:

{

    "ObjetoPaiGeral":[
        {
            "ObjetoSubPai":{
                "ObjetoFilho":1
            }
        },
        {
            "ObjetoSubPai":{
                "ObjetoFilho":true
            }
        },
        {
            "ObjetoSubPai":{
                "ObjetoFilho":"string"
            }
        }
    ]

}

It can be easily stored inside a variable as an Object, thus making its usability easy, being able to access values programmatically, as for example in Javascript declaring and accessing the last example above:

var JSONObject = {

        "ObjetoPaiGeral":[
            {
                "ObjetoSubPai":{
                    "ObjetoFilho":1
                }
            },
            {
                "ObjetoSubPai":{
                    "ObjetoFilho":true
                }
            },
            {
                "ObjetoSubPai":{
                    "ObjetoFilho":"string"
                }
            }
        ]

    };

Accessing values:

JSONObject;                                            //objeto geral em si
JSONObject.ObjetoPaiGeral;                             //array dos sub pais
JSONObject.ObjetoPaiGeral[0];                          //acessando o primeiro filho do pai geral
JSONObject.ObjetoPaiGeral[0].ObjetoSubPai;             //acessando o objetosubpai do primeiro filho do pai geral
JSONObject.ObjetoPaiGeral[0].ObjetoSubPai.ObjetoFilho; //aqui você tem um valor, que é o valor do objeto filho do sub pai que é filho do pai geral.
//Você pode utilizar o tamanho do Array para fazer um laço de repetição se quiser:
JSONObject.ObjetoPaiGeral.length; //retornará 3.

It is currently one of the best methods to rescue server information, mainly in an application that requires real-time data update.

You can learn more about it here at Official Website of JSON.

21

JSON is an acronym for "Javascript Object Notation", a lightweight format for computer data exchange. JSON is a subset of Javascript object notation, but its use does not require Javascript exclusively.

It is a javascript notation, which can be written in a text file, such as a file XML. Can be used for the exchange of information through webservices. As it is lighter than XML, it is increasingly used.

Join means join. It can be for join two tables of a database, join texts and etc. It is a fairly generic term that may have different meaning in each technology.

http://en.wikipedia.org/wiki/JSON

6

JSON is a hierarchical data encoding method, such as XML, although simpler.

JSON was born within the context of Javascript -- and being valid Javascript can be directly interpreted with Eval(), although this is dangerous for security reasons. It is also interpretable directly in Python. but today is considered a generic method and supported by all programming language.

6

JSON is the acronym for Javascript Object Notation.

This means that it uses text formatting that is similar to the declaration syntax of an object in Javascript language.

This text can be used in various ways to structure any object in several situations. In general it is stored somewhere (can be a simple file, database or otherwise) or transmitted from one application to another location or remotely.

Contrary to popular belief, and to be the most common use, it is not only used to transmit data via the web.

Although it is based on the syntax of JS does not mean that it needs it to use, only the syntax is very similar, and this data, because this is a given (or a list of them because it is possible to even have an array within the format), can be processed by any language using a standard library that understands the format or even manually if the programmer wants it (it takes a lot of work and is at risk in most situations).

It is true that it was originally created to work with JS, but it was universally adopted.

There are competitors of this format, each with advantages and disadvantages, some more powerful, or more flexible, but simple to use, more robust or with other features that may interest the user of it (the programmer). YAML, BSON, XML and CSV are just some of the best known.

But it is important to stress that it is only a data format. It cannot be confused with the object created in JS. Both are declared with the "same" syntax, only that. And of course, if the syntax is similar to semantics is also, but it is more limited.

Just as the object of the JS it defines the whole structure of the data, through pairs of key and value (it is possible that the key is implicit acting as if it were a array), where the value can take various forms using the basic typing adopted by JS, and of course the syntax to define a value in each type. Therefore JS has full compatibility. Other languages may have some impedance and need some adaptation of some kind, although because they are basic types this should not be frequent, nor a difficult problem to solve.

Being a text is easy to read by humans and easy to process, although it is not efficient neither in size nor to process. In general a process of serialization or deserialization is performed to convert this format into an application object.

There’s a official website which demonstrates the exact syntax adopted. And as you can see there is a official specification. There is also a list (probably not very updated) with implementations in several languages to manipulate this format.

Differences for a Javascript object

One of the most important differences for the JS object is that JSON only accepts type keys string. And official syntax requires the use of double quotes to delimit a string.

JSON accepts duplicate keys, even because it is only a format, there is no actively prohibiting it, and each implementation will have to deal with it the way it thinks best when creating an object in the application when it does not accept duplicate key.

Obviously the format only accepts literal values, can not create expressions to be executed, even can not use functions, at least in official JSON.

So every JSON generates a compatible JS object, but not every JS object can generate a standard JSON.

The term JSON Object does not exist. I don’t know a language that has a type called JSON, but it can exist, probably it would be used to facilitate the conversion to another object.

5

An important point that was not addressed in the other replies: a valid JSON nay must be a set of key/value pairs. All right it is the most commonly used format, but do not want it to be the only one possible. But let’s go by parts...


Format specification

JSON, as the other answers have already said, is only a data format, whose syntax is inspired by Javascript - it would only be a "subset", because in Javascript the syntax is more flexible and with more possibilities (as already pointed out in another answer - and at the end there are also some more examples).

Although JSON is acronym for "Javascript Object Notation", does not mean that it can only be used with Javascript (many languages have format support, either native or through libraries).

There are some "official" documents that describe the format:

A common point is that they all describe JSON as being text in a specific format. RFC’s describe it this way:

Javascript Object Notation (JSON) is a lightweight, text-based, language-Independent data Interchange format. It was derived from the Ecmascript Programming Language Standard. JSON defines a small set of formatting Rules for the Portable representation of Structured data.

And ECMA 404 describes it like this:

JSON is a lightweight, text-based, language-Independent syntax for Defining data Interchange formats. It was derived from the Ecmascript Programming language, but is Programming language Independent.

The definitions therefore say that it is a text format language-independent, that was derivative of language Ecmascript (that in the background is the Javascript that we know). That is, the syntax is inspired/based on Javascript (but it is not 100% identical, because Javascript allows variations that are not valid JSON’s), but the format can be - and nowadays is - used in other languages.

Another important point is that they all define that JSON is a data Interchange format (format for data exchange/exchange). That is, although it is widely used on the Web, it is not its only purpose. Any application that needs to exchange data with another can use it. In this aspect, it is not very different from other formats such as XML, CSV, YAML, etc..

And another detail is that the specifications refer to the data using the term "JSON Text", since it is a text-based format (text-based). Informally I see people refer to it only as "JSON" (as in "This API returns a JSON", which technically means that it returns a JSON Text). That is, in the background, a JSON is a "string" (a string of characters), which represents the data in a specific format. This is an important distinction: a JSON is not a Javascript object (it can be converted from/to, but is not).

In addition to the documents already cited, there is also the official website, using the definition of ECMA 404.


Values (JSON Values)

Another common point is the definition of valid values, which are called generically JSON values. All of the above documents define that a JSON value can be an object, array, string, number, or one of these 3 literals: true, false and null.

Heed: It is worth remembering that here the term "object" should not be confused with the subject to the programming languages. Not least because in Javascript, an array is also an object, but the JSON format definition treats these terms as different things. So in the excerpt below, when I refer to "object" and "array", I’m talking about the definitions of RFC’s and ECMA 404 (i.e., forget Javascript - and any other language - for the next few paragraphs).


The most, shall we say, basic types of JSON values are the numbers and strings. The full definition can be found in the above mentioned links, but basically a number can be represented by literals such as 42, -10.56, 6.02e24 (cienfítica notation), among others. And a string is a string of characters between double quotes (besides allowing the escapes as \n, \t, and \uXXXX to represent code points hexadecimally).


An object is a set of key/value pairs, bounded by keys ({ }). Each pair has a key and its value, separated by two-points (:), and the pairs are separated by comma. This is the "most common JSON" that is used (and that many think is the only way possible). Keys can only be strings (a string between double quotes), and values can be any JSON value.

Example:

{
    "nome": "Fulano",
    "idade": 42,
    "aprovado": false,
    "filiação": {
        "pai": "Ciclano",
        "mãe": "Beltrana"
    }
}

In this case, the above object has 4 keys: "name", whose value is the string "Fulano", "age", the value of which is the 42, "approved", the value of which is the literal false, and "parenting", whose value is another object (which in turn has 2 keys: "father" and "mother", whose values are strings respectively "Ciclano" and "Beltrana").


An array is a sequence of JSON values comma separated and bounded by square brackets ([ ]). Ex:

[ "Fulano", 42, false, { "pai": "Ciclano", "mãe": "Beltrana" } ]

In this case, the array above has 4 elements: the string "Fulano", the number 42, the literal false and an object (which in turn holds the keys "father" and "mother" and their respective values "Ciclano" and "Beltrana"). There is nothing in the format specification that prevents the values from being like this, of different "types" (implementations can treat it however they want).

Remember also that as objects and arrays may have any JSON values, then they can be nested to each other: we can have arrays containing objects, whose values can be other objects or arrays, etc. There is no theoretical limit to nesting structures, but implementations can define one. According to RFC 8259: "An implementation may set Limits on the Maximum Depth of nesting".


What is a valid JSON?

RFC 4627 (the oldest and currently obsolete) defines that a valid JSON can only be an object or array (remembering that I am still referring to the "object" and "array" explained above, and not to the definition of a specific language). That is, the most common format (the object, the set of key pairs/value) is not the only possibility. Therefore, an array like [1, 2, 3] is a perfectly valid JSON.

The RFC’s 7159 and 8259, and the ECMA 404 go further, and define that any JSON value is a valid JSON. That is, both 42 how much "Ok" or true, any of these values is considered a valid JSON.

But of course, to function properly, you need to know the implementation details of the language you are using, to make sure they can handle any JSON values (some older implementations followed RFC 4627, for example, while others may include "extensions" and accept formats not defined by RFC). But as far as I know, today most languages mainstream support the latest specification and accept any JSON value without problems. For example, in Python those JSON values already are mapped to specific language types:

import json

x = json.loads('42')
print(x, type(x)) # 42 <class 'int'>

x = json.loads('"abc"')
print(x, type(x)) # abc <class 'str'>

x = json.loads('false')
print(x, type(x)) # False <class 'bool'>

x = json.loads('null')
print(x, type(x)) # None <class 'NoneType'>

I also tested in Javascript, PHP and Java (using the library Gson), and all accept the JSON values above. Including, some documents quote the RFC 7159, and therefore consider that any JSON value is a valid JSON.

Anyway, although the object (set of key pairs/value) is the most common choice - especially nowadays, the overwhelming majority of API’s I see around opt for it - is not the only option. I recognize that in many cases this can be the most useful format as it provides a description of the information ({"nome": "Fulano", "idade": 42} seems clearer to me than just ["Fulano", 42]), but I see that often this is abused. A classic example, we have an API whose URL is /users and returns the following:

{
    "usuário 0": { "nome": "Fulano", "idade": 42 },
    "usuário 1": { "nome": "Ciclano", "idade": 20 },
    "usuário 2": { "nome": "Beltrano", "idade": 30 }
}

The "user X" keys do not add any relevant information - if the URL is /users, I already know it returns user data, so the return could be an array:

[
    { "nome": "Fulano", "idade": 42 },
    { "nome": "Ciclano", "idade": 20 },
    { "nome": "Beltrano", "idade": 30 }
]

Of course it is only an illustrative example and the analysis should be done case by case, depends on the requirements, etc. But it is only to show that not always a single object (a large set of key pairs/value) is the most suitable (another example).


Differences between JSON and Javascript

Just to finish, some more differences (besides those already mentioned in other answers) between the JSON format and the Javascript syntax.

In Javascript we can have many more variations that a JSON does not allow:

function nomeChave() {
    return 'bla';
}
var chave = 'idade';

// Este é um objeto JavaScript válido, mas um objeto JSON inválido
var obj = { // JavaScript aceita comentários, JSON não :-)
     // não precisa de aspas na chave, e string pode usar aspas simples
    nome: 'Fulano',
    // nome da chave pode estar em uma variável, e o valor literal pode ser "undefined"
    [chave]: undefined,
    // chave é uma expressão que resulta em uma string, e o valor é o resultado de uma expressão
    [nomeChave() + 'xyz']: new Date(123459 * 2300),
    // o número é convertido em string, e o valor é uma regex
    2 : /[a-z]+/,
    // o valor é uma função
    func: function() { console.log('oi'); }
};

console.log(obj); // { "2": /[a-z]+/, "nome": "Fulano", "idade": undefined, "blaxyz": "1970-01-04T06:52:35.700Z", "func": function() { console.log('oi'); } }

Now, if I did a JSON like that, it would be invalid:

{
    nome: 'Fulano',
    [chave]: undefined,
    [nomeChave() + 'xyz']: new Date(123459 * 2300),
    2 : /[a-z]+/,
    func: function() { console.log('oi'); }
}

Of course you can use JSON.stringify to convert obj for a valid JSON, but the result will be in accordance with the format specified by ECMA 404 (many values will be converted to string or some other valid type, for example, although the function is ignored by default - but it is possible to customize this behavior).

Anyway, know separate the format (which in the background is only a specification) from its implementations, especially Javascript. Each language will have implementation details that may or may not be the same as others.

For example, the specification says nothing about the uniqueness or order of the keys, it is up to each language/library to handle it the way they see fit. A number like 13245678913246789, How will he be interpreted? Some languages have specific types according to number size, others have only a single numeric type, while others may simply not accept values above a certain limit. The specification leaves all this open, and each language deals with the way it thinks best (in the background, it is a concern you will always have when sending data between applications, regardless of the format chosen).

4

Json and Join are completely different things.

Join is used in a database when you want to return data from multiple tables that have relationships between them. Should be used when you want to get data that is not in a table only.

Already the Json "uses Javascript syntax to describe data objects, but is still platform independent." In this case, it is used when you want to exchange data between applications. The Json format is widely used in the Front-end environment for information exchange with the Back-end

  • It was confusing to see "Join" in the most recent versions of the question. I could only understand why of your answer by checking the history of the question

Browser other questions tagged

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