The terms JSON and object (and even JSON object ) are often used interchangeably when talking about a data structure, especially in AJAX-related contexts.
- What is the difference between both?
- Is a JSON a Javascript object or is it something else?
The terms JSON and object (and even JSON object ) are often used interchangeably when talking about a data structure, especially in AJAX-related contexts.
I assume that the reader has some basic knowledge of Javascript:
They are not the same
JSON is the acronym for JavaScript Object Notation , it is a lightweight text format for data exchange. What does this mean? Well, if we see the following text
Every programmer is clear that this is a text in XML format . Well, JSON is nothing more than a different format but with the same function. The equivalent of that XML could be something like:
As its name suggests, this notation is similar to what we would use in Javascript to create an object :
But a JSON is, and here I am repeating myself, text :
The JSON format is somewhat more restrictive than Javascript code would be:
<!-- Comentarios-->
)undefined
.And how do we transform the text into a manipulable object? And how do we do the reverse operation?
Using the following functions:
JSON.parse(<texto>)
It returns an object created from a string that is in JSON format.JSON.stringify(obj)
It returns a string in JSON format with the attributes of the objectobj
. Ifobj
it has attributes that are functions, they will be ignored.Therefore, although JSON originates from the Javascript language, it is nothing more than a way of sending data between applications, which will not necessarily be implemented with Javascript: any programming language can process a JSON (just like an XML) to obtain the needed information.
Two everyday examples of using JSON are:
localStorage
or the , the andsessionStorage
methods only work with the type , so it is necessary to transform the objects that we want to save to text.setItem
getItem
string
I would like to give a more colloquial answer, something you could give as an example to a non-programmer or beginner.
- Object: it is limited to the code, it is initialized and it is worked with the object during the execution of a program. The object will be formatted according to the semantic rules of the corresponding (object-oriented) language in which the code in which the objects are defined is written.
- JSON: is the 'file' that is used as input-output, to initialize or save states or values of an object and as it is a 'standard', it has its own defined semantic rules. This standardization of the format makes JSON compatible across different programming languages.