Hay tantos lenguajes de programación y cada lenguaje tiene sus propias características. Pero todos tienen una cosa en común: procesan datos. Desde una simple calculadora hasta supercomputadoras, todas trabajan con datos.
Lo mismo ocurre con los humanos: hay tantos países, tantas culturas y tanto conocimiento dentro de cada comunidad.
Pero para comunicarse con otras comunidades, las personas necesitan un medio común. El lenguaje es para los humanos lo que JSON es para la programación, un medio común de transmisión de datos.
¿Qué es JSON?
JSON son las siglas de J ava S cript O bject N otation. Entonces, antes de comprender JSON, comprendamos los objetos en JavaScript.
Cada lenguaje de programación tiene algún método para almacenar datos similares juntos. En C, por ejemplo, se les llama estructuras.
En JavaScript, los objetos son una colección de pares clave-valor, donde los valores pueden ser cualquier variable (número, cadena, booleano), otro objeto o incluso una función. Los objetos son muy útiles en la programación orientada a objetos.
La programación orientada a objetos es un paradigma de programación basado en el concepto de "objetos", que pueden contener datos, en forma de campos, y código, en forma de procedimientos.Veamos un ejemplo.
En JavaScript, los objetos se definen mediante llaves, por ejemplo:
var obj = {};
Aquí, obj
hay un objeto vacío. También puede crear objetos usando constructores, por ejemplo:
function Student(name, roll_number, age) { this.name = name; this.roll_number = roll_number; this.age = age; } var student1 = new Student("Abhishek", "123", 18); console.log(student1.name, student1.roll_number, student1.age);
Esto daría la salida Abhishek 123 18
.
Así es como creas objetos en JavaScript. Pero estos objetos siguen siendo variables que solo son específicas de JavaScript.
Si desea exportar estos objetos y, por ejemplo, enviarlos a un servidor, necesita un método para codificarlos. Veamos cómo se hace.
JSON Stringify
Para transmitir datos de un dispositivo a otro y de un idioma a otro, necesitamos una convención estructurada, uniforme y bien definida.
Aunque JSON se basa en objetos JS, ciertas condiciones deben ser válidas. Afortunadamente, no tiene que preocuparse por esas condiciones, porque en JavaScript, tenemos un método llamado JSON.stringify()
.
Este método se utiliza para convertir un objeto JS en una cadena codificada que se puede transmitir a cualquier lugar sin perder ningún dato.
Puede parecer mágico que cualquier objeto pueda codificarse en una cadena y enviarse a cualquier lugar. Entendamos más en profundidad a través de algunos ejemplos.
Este es el prototipo del método stringify:
JSON.stringify(value[, replacer[, space]])
El primer parámetro es value
cuál es el objeto que desea secuenciar. El segundo y tercer parámetro son opcionales y se pueden usar si desea personalizar cómo se codificará (por ejemplo, el separador y la sangría).
Intentemos encadenar nuestro ejemplo anterior.
function Student(name, roll_number, age) { this.name = name; this.roll_number = roll_number; this.age = age; } var student1 = new Student("Abhishek", "123", 18); var str = JSON.stringify(student1); console.log(str);
Esto dará la salida {"name":"Abhishek","roll_number":"123","age":18}
.
Si utilizamos los parámetros opcionales, es decir reemplazamos JSON.stringify(student1)
con JSON.stringify(student1, null, 2)
, obtendremos algo como esto:
{ "name": "Abhishek", "roll_number": "123", "age": 18 }
Puede utilizarlos para imprimir JSON en un formato legible. Probemos ahora con un ejemplo más.
Aquí usaremos métodos de objeto. Los métodos de objeto son funciones dentro de un objeto que se pueden llamar con ese objeto, usando los métodos en nuestro ejemplo anterior:
function Student(name, roll_number, age) { this.name = name; this.roll_number = roll_number; this.age = age; this.print = function() { console.log(this.name, this.roll_number, this.age); } } var student1 = new Student("Abhishek", "123", 18); student1.print();
Esto le dará el mismo resultado que primero ejemplo, que es,
.Abhishek 123 18
Los métodos de objeto se pueden utilizar para ejecutar funciones asociadas con un objeto y utilizar las propiedades del objeto. Intentemos secuenciar este objeto.
function Student(name, roll_number, age) { this.name = name; this.roll_number = roll_number; this.age = age; this.print = function() { console.log(this.name, this.roll_number, this.age); } } var student1 = new Student("Abhishek", "123", 18); var str = JSON.stringify(student1); console.log(str);
Es todavía le dará la misma salida,
.{"name":"Abhishek","roll_number":"123","age":18}
Por lo tanto, la función stringify ignora los métodos de objeto. Si desea que también se transmitan, primero debe convertirlos en una cadena.
Por ejemplo, puede llamar student1.print = student1.print.toString()
y luego secuenciar. Entonces obtendrías algo como esto:
{"name":"Abhishek","roll_number":"123","age":18,"print":"function() {\n console.log(this.name, this.roll_number, this.age);\n }"}
Consideremos otro objeto:
var obj = {}; obj.key1 = "value1"; obj.key2 = obj; var str = JSON.stringify(obj); console.log(obj);
Esto arrojará un mensaje de error Uncaught TypeError: Converting circular structure to JSON
.
This happens because key2 is referencing back to obj. Such objects are known as circular objects, and they cannot be converted to a JSON string.
This is where the second parameter comes in handy. Although I won't demonstrate how it works here, you can find the solution on this MDN page.
This is how you encode JSON. Now let's see how to parse a JSON string.
JSON parse
Just how JavaScript has a function to stringify JSON, we also have a function to parse that stringified JSON. This is the function prototype:
JSON.parse(text[, reviver])
Here, the first parameter is the JSON string which needs to be parsed. The second parameter is optional, and can be a function to modify the parsed JSON before returning. Let's demonstrate this method using an example.
function Student(name, roll_number, age) { this.name = name; this.roll_number = roll_number; this.age = age; } var student1 = new Student("Abhishek", "123", 18); var str = JSON.stringify(student1); var parsedJSON = JSON.parse(str); console.log(parsedJSON,name. parsedJSON.roll_number, parsedJSON.age);
And the output will be
, so the JSON string was successfully parsed. Abhishek 123 18
You could use this to send data from client to server. The data to be sent can be JSON encoded at the client and the stringified JSON will be parsed at the server and processed. This makes it really easy.
JSON can also be used to transmit data across different programs written in different languages. All languages have libraries to stringify and parse JSON.
JSON vs. XML
XML or eXtensible Markup Language is a very popular way of storing and transmitting data, similar to JSON. It existed before JSON and is still widely used today.
For example, it's used in RSS feeds, which are still the most popular way of subscribing to some publication or author. There are also XML sitemaps which are a list of all pages on a website. And search engines use them to see if there are any new pages to be crawled.
XML uses markup format – similar to HTML but much stricter.
JSON and XML have various similarities and differences, as explained in the following points:
- Both are human-readable
- Both have a hierarchial structure
- Both are widely supported across various programming languages
- Both can be fetched from the server using HTTP requests
- JSON is shorter than XML
- JSON can use arrays
- JSON can be parsed using standard JavaScript functions, whereas XML needs to be parsed using the XML DOM (which is slower)
The same data can be expressed in JSON and XML as follows:
JSON:
{"employees":[ { "firstName":"Quincy", "lastName":"Larson" }, { "firstName":"Abigail", "lastName":"Rennemeyer" }, { "firstName":"Abhishek", "lastName":"Chaudhary" } ]}
XML:
Quincy Larson Abigail Rennemeyer Abhishek Chaudhary
JSON es mejor que XML por muchas razones, pero eso no significa que debamos abandonar XML. Aún así, JSON se convertirá en la forma preferida de transmisión de datos en el futuro.
JWT: el futuro de JSON
JSON Web Token (JWT) es un estándar abierto que define una forma compacta y autónoma de transmitir información de forma segura entre las partes como un objeto JSON.Esta información se puede verificar y confiar porque está firmada digitalmente. Los JWT se pueden firmar usando un secreto (con el algoritmo HMAC) o un par de claves pública / privada usando RSA o ECDSA.
Estos tokens se pueden utilizar para firmar datos JSON y verificar la identidad del remitente. Dado que los datos están firmados, si se ha manipulado algún dato, lo sabrá de inmediato.
Though we won't discuss the implementation in full here, we can understand how it works. A JSON Web Token consists of three parts, the header, the payload and the signature.
The header consists of the type of token and algorithm used, the payload consists of the data, and the signature is the value you get when you sign the header and payload together.
The final token is in the form of ..
.
These tokens are currently used in authorization and are faster and more compact than other authorization methods. These may be very useful in the future and their potential is very high.
Conclusion
In this article, we've seen the importance of JSON as a medium of data transfer between completely different systems, and why is it so convenient.
JSON is a universal medium and is not just specific to JavaScript. JSON is already used in NoSQL databases to store data in JSON format.
We also compared JSON and XML and saw why JSON is more efficient and faster than XML. In the future, we may develop even better ways of transmitting data.
The rate at which the internet is growing, efficient data transfer will be the highest priority. And JSON serves that function really well for now.
You can try new things with JSON and implement different data structures – it's open to innovation, and we should never stop experimenting.
Hope you liked my article. I have learned a lot by writing it, and your appreciation motivates me everyday, Do visit my internet home theabbie.github.io.