Code

JSON: What is this format and how to use it

JSON: What is this format and how to use it / Skillbox Media

Get Python programming skills without spending money ➞ Master Python and learn how to create Telegram bots, web parsers, and websites from scratch with a free course from a Sber expert.

Learn more

JSON, or JavaScript Object Notation, is a widely accepted text format used to store and transmit structured data. This format is based on, but is not limited to, JavaScript object syntax. Modern programming languages ​​such as Python, Java, and several others support this format.

Before JSON was introduced, interacting with a server required constantly refreshing the page in the browser, which significantly slowed down websites. However, with the advent of AJAX requests using JSON, it became possible to perform these operations in the background without requiring a page reload. This innovation significantly increased the speed of working with Internet resources, and JSON took the position of the standard for transmitting data on the network.

Today we will get acquainted with the JSON format.

  • how the format appeared;
  • its advantages compared to other formats;
  • the basic principles of construction and rules of the language;
  • objects and arrays;
  • JSON5 is an extension of the JSON (JavaScript Object Notation) format, which introduces additional features and simplifications for working with data. Unlike its predecessor, JSON4, JSON5 offers more flexible syntactic constructs, allowing, for example, the use of comments, the unquoting of keys if they are valid identifiers, and support for more complex data formats, such as multi-line strings.

    The main difference between JSON5 and JSON4 is that JSON5 focuses on improving the readability and writeability of data, making it more suitable for configuration files and other use cases where understandability is important. JSON4, on the other hand, is a more strict and traditional format, which can complicate its use in some scenarios. Thus, JSON5 is more modern and tailored to the needs of developers, offering more options for working with data.

  • JSON Schema is a tool for describing the structure and content of JSON data. It allows developers to formalize data requirements by defining which fields must be present, their types, and the possibility of additional properties. JSON Schema can be used not only to validate data but also to document an API, making it more understandable for users. This standard helps ensure consistency and predictability when working with JSON, simplifying the development process and interaction between different software components.
  • How to work with JSON;

How JSON Came to Be

Douglas Crockford, an American programmer widely known for his role in the development of JavaScript, is considered the founder of the JSON format. He is also the creator of the well-known static code analyzer JSLint and the author of such books as «JavaScript: The Good Parts» and «How JavaScript Works».

Douglas CrockfordPhoto: Wikimedia Commons

“I was introduced to the JSON format. I can't say I invented it, because it already existed before me. I just discovered it, gave it a name, and explained how to use it. I know that other people made this discovery as well, at least a year before me. The first case I know of is at Netscape, where someone was using JavaScript array literals to pass data back in 1996, so at least five years before I came up with the idea myself.

Douglas Crockford, a renowned developer and programming expert, played a key role in the creation and popularization of the JSON format, which has become an integral part of modern web development. His work, known as the "JSON Saga," covers the historical context, evolution, and usage of this lightweight data interchange format.

JSON, an acronym for JavaScript Object Notation, was designed as a simple and convenient way to represent structured data. It became an alternative to more complex formats such as XML due to its simplicity and readability. Crockford, recognizing JSON's potential, actively promoted its use, emphasizing its benefits for developers and applications.

During his career, Crockford not only adopted JSON into various technologies but also became its advocate, explaining how the format could improve interactions between clients and servers. Thanks to his efforts, JSON gained widespread adoption and became the standard used in many modern APIs.

Thus, Douglas Crockford's contributions to the development of JSON and his philosophy of simplifying data exchange have had a significant impact on programming and web development, providing developers with a powerful tool for creating more efficient and user-friendly applications.

In early 2001, Douglas Crockford and Chip Morningstar founded a company called State Software. While working on various projects, they encountered a serious problem: transferring data between the server and the browser required constant page refreshes, which negatively impacted performance.

Various methods were used to solve this problem, including specialized browser plug-ins based on Flash and Java applets. However, interacting with them proved labor-intensive and often error-prone.

At that moment, Crockford recalled a concept he'd once heard from a Netscape employee. He decided to integrate a JavaScript object into the HTML code that sent a message to the web page. The initial version looked like this:

The code intended to pass a message from a child window to its parent via the parent object failed because the word do is reserved in JavaScript. To solve this problem, Crockford used quotation marks, wrapping all the keys inside an object.

Thus, a new format was born, which was initially planned to be called JSML (JavaScript Markup Language), but JSON (JavaScript Object Notation) was eventually chosen.

In 2001, Crockford created a web page where he detailed this format, allowing all programmers to use it in their projects.

"When I created JSON, I was guided by the principles of minimalism. I believed that if we reduced the number of things that needed to be agreed upon, it would increase the chances of easier interoperability between us. My goal was that the JSON standard could be put on the back of a business card."

Douglas Crockford is a well-known figure in the fields of technology and programming, particularly for his contributions to the development and popularization of the JavaScript language. He actively shares his knowledge and ideas through various platforms, including Hackernoon, where he publishes articles and thoughts that help grow the developer community. His work often emphasizes principles of good design and code optimization, making it useful for both beginners and experienced programmers.

The JSON standard on the back of a business card Photo: Eric Miraglia / Flickr

JSON stood out from its peers—such as XML, CSV, and YAML—due to its concise syntax and compact file size, making it particularly suitable for use in web applications. This has led to its rapid growth in popularity.

Number of requests on StackOverflow Infographic: Stack Overflow Trends

In 2014, the ECMA standards organization officially approved the JSON format, developing its specification. Currently, this format has become a key means for exchanging data between web servers and browsers.

In this section, we will look at the correct pronunciation of the term JSON, which raises many questions among developers. There are two pronunciation methods: with the accent on the "e" and with the accent on the "o". One of the creators of this format, Chip Morningstar, can best answer this question.

“I often hear people pronounce my name as “JaysOn,” and it always amuses me. Every time I’m at an event and someone addresses me that way, I correct them with a smile: “Jason.” They are usually surprised and ask, “How did you know that?” And I answer: "Because I invented it."

Chip Morningstar, a renowned developer and innovator in the field of computer technology, left a significant mark on the history of digital entertainment and programming. His contributions to the development of virtual worlds and massively multiplayer online games had a huge impact on the industry. During his career, he was actively involved in the creation of unique projects that changed the concept of user interaction in the digital space.

Among his achievements, one can note the creation of one of the first massively multiplayer online games in which players could interact with each other in real time. This innovation opened new horizons for gamers and developers, laying the foundation for modern MMORPGs.

Morningstar also paid attention to design and user experience, which allowed him to create not only game mechanics but also emotionally rich worlds. His work inspired an entire generation of programmers and designers striving to create more interactive and immersive virtual spaces.

Thus, Chip Morningstar not only became a pioneer in his field, but also had a significant influence on shaping the future of digital entertainment, leaving a bright mark on the history of programming and game design.

Advantages of JSON

JSON is not the only way to exchange data. Alternatives include XML and YAML, which are also used by developers. However, JSON has a number of advantages that distinguish it from these formats:

The syntax, which is distinguished by its simplicity and ease of perception, is understandable for both humans and computers. You don't have to be a JavaScript expert to master the art of writing and interpreting data. You'll see soon enough.

Compactness and simplicity. Compared to files of other formats, JSON files are smaller in size and load faster. Research shows that modern browsers can process JSON tens of times faster than XML.

There is no need to be tied to a specific programming language. Almost any common language, such as Python or Java, is suitable for working with JSON.

Variety of data types. JSON is suitable for storing arrays, sequences, and sets of key-value pairs. However, this is far from all its capabilities. This format is also excellent at representing complex data structures, such as trees and hierarchical structures.

Wide browser compatibility. All current web browsers provide support for the JSON format.

Standalone documentation. The JSON format allows you to add metadata that characterizes the contained data, making it more convenient to use.

The Organization and Grammar of the JSON Format

The syntax of JSON is similar to the syntax of a regular JavaScript object: information is represented as key-value pairs, separated by commas. It is important to remember that there should not be a comma after the last pair - this is a common mistake that can be quite difficult to detect.

Keys are string variables, while values ​​​​can take various forms: strings, numbers, booleans, objects, arrays, or null. The standard JSON format does not support functions and dates.

An example of a simple JSON file is the following format:

Although the JSON format is originally based on JavaScript, its specification allows for some elements that are not allowed in JavaScript. For example, in JSON, characters that separate lines and paragraphs can be written without the need for escaping.

When working with dates in JSON format, it is important to convert them to a string format that complies with the ISO 8601 standard.

A full description of JSON syntax requirements is available on the Datatracker platform. To ensure that the syntax is correct or complies with established standards, there are many online validators, such as JSON Validator.

JSON Data Structures: Objects and Arrays

In JSON, data is organized using two main structures: objects and arrays.

Objects are unordered collections. They do not care about the order of key-value pairs, which allows them to be rearranged. However, be careful! When a programmer moves a key-value pair from any position to the end, they often forget to remove the comma, which can lead to an error.

A JSON object is similar to objects in JavaScript, however, keys must always be enclosed in quotation marks. For example:

Arrays are an organized collection of elements. Their visual representation looks like this:

In the context of arrays, the order of elements plays a significant role. Unlike objects, arrays do not have keys, which means that to access values, you must use the index of the corresponding element. It is necessary to take into account that the index of the first element starts from zero.

Objects and arrays can contain each other, and there is no limit to the number of levels at which this can occur.

What is JSON5

JSON5 is an improved version of the JSON standard that makes the process of reading and writing data more convenient and understandable. In addition, it offers new features such as the ability to add comments, which is missing from the original standard.

Key features of JSON5 that may be useful when working with:

Please provide the text you want to rewrite.

Quotation marks for keys are optional, but they can be omitted if the key consists exclusively of letters, numbers, or underscores and is not a reserved word.

There is a specific standard for writing dates and times:

The system allows for multi-line texts, which makes it possible to enter strings without the need for complex escaping.

Provides the ability to use underscores in numbers for increased readability.

Provides support for hexadecimal and octal number systems.

However, it should be kept in mind that not all parsers, applications, and libraries support JSON5, which is currently holding back its adoption.

Understanding JSON Schema

There is a specialized language called JSON Schema, designed to describe and verify data in JSON format. Let's imagine we have a standard JSON file:

The developer is faced with uncertainty regarding required fields, data types, and other characteristics of values. JSON Schema provides the ability to integrate important metadata, as well as establish "rules" for this information. This allows you to clearly specify which fields must be filled in and what data they can contain.

JSON Schema serves as a tool for data validation when exchanging information between different systems or when working with data received from users. If new data does not conform to the established schema, the developer promptly receives an error notification, allowing them to thoroughly analyze the information, make the necessary corrections, or request an update.

This code ensures reliability, predictability, and error tolerance, allowing for clear data formatting requirements. An example of what the above file would look like is provided using JSON Schema:

Let's walk through the code line by line.

  • The first sentence provides a link to a version of the JSON Schema specification.
  • The information must be of the "object" class.
  • The object must include three required attributes: "name", "age", and "address".
  • Each field has its own data type: "string" is used for name, "number" for age, and "object" is used for address.
  • The "address" field must be an object and must include two required subfields: "city" and "zip", which must be of the string data type.

How to Work with JSON

Knowledge of working with JSON files is fundamental for programmers, as This format serves as the primary standard for transmitting data in web and mobile applications.

Basically, interacting with the JSON format involves two key processes: serialization and deserialization. Let's take a closer look at them.

Serialization is the process of converting data from its native format, such as a JavaScript object, into the JSON format that can be transmitted to the server. Most programming languages ​​offer built-in methods or libraries to accomplish this task. In JavaScript, for example, converting an object named person to a JSON file would be done like this:

Deserialization, in contrast to serialization, converts information from the JSON format back into a structure that the programmer can use in their code.

What to Remember

Let's review everything we've learned about the JSON data format:

  • JSON is a widely accepted text-based format for storing and exchanging structured data. It is most widely used in the field of web technologies.
  • Information in the JSON format is organized into key-value combinations.
  • JSON uses two key structures to organize data: objects and arrays. Objects are unordered collections, while arrays are ordered.
  • JSON5 offers additional features compared to the traditional format, but is not currently supported by web browsers.
  • JSON Schema serves as a tool for describing data requirements, allowing developers to determine which fields are required and what formats are acceptable for them.
  • There are two key methods for working with JSON: the first is serialization, which allows you to convert JavaScript or other programming languages ​​into the JSON format. The second method is deserialization, which does the opposite: it converts JSON data back into plain code.

If you're interested in learning more about programming and code, join our Telegram channel!

Read also:

  • Ways to Convert HTML to JSON: Developing a Functional JavaScript Application.
  • API, or Application Programming Interface, is a set of rules and protocols that allow different software systems to interact with each other. It serves as an intermediary that simplifies the exchange of data and functionality between applications.

    The main idea of ​​an API is to provide a standardized way to access functions and data, eliminating the need for complete code rewrites. This allows developers to integrate third-party services and components without having to dive deep into their internals.

    APIs work based on requests and responses. When one application wants to retrieve data or call a specific function in another application, it sends a request through an API. This request typically includes information about what exactly is needed and may contain parameters to refine the request. The API then processes the request, interacts with the required service, and the result is returned as a response containing the requested information or confirmation of the action.

    Thus, the API simplifies development, allowing you to build more complex systems using existing solutions, significantly accelerating the software development process.

  • Changes in PHP developer salaries in Russia in 2023: analytics from Skillbox Media.