How is the yaml data format structure different from json
How is the yaml data format structure different from json
Yaml vs. Json — что круче?
Сегодня поговорим об интересном (и таинственном для фронтов) формате YAML. Он считается одним из наиболее популярных форматов для файлов конфигураций.
Цель этой статьи — познакомить вас со структурой YAML, помочь понимать, читать и изменять YAML-файлы. Для тех, кто уже знаком с форматом — напомнить про некоторые его особенности. И сравнить YAML с JSON.
Цели создания
Сообщество разработчиков устало от «зоопарка» различных форматов для конфигов, им хотелось упростить себе жизнь и прийти к единому понятному формату. И в 2001 году Кларк Эванс создал YAML 1.0.
Его основные цели:
Рис.1. Определение из официальной документации
Сейчас последняя версия — YAML 1.2, и она в основном используется как формат для файлов конфигурации Ruby on Rails, Dancer, Symfony, GAE framework, Google App Engine и Dart. Также YAML является основным языком описания классов, ресурсов и манифестов для пакетов приложений OpenStack Murano Project и Swagger.io.
YAML vs. JSON
По сути YAML — это расширенная версия известного нам формата JSON.
Чтобы лучше разобраться в формате, давайте сначала рассмотрим пример JSON-конфига:
Этот файл очень легко читается, мы можем быстро определить, что к чему, но … нужно знать, что у JSON-формата есть некоторые ограничения:
Попробуем переписать наш пример в формате YAML. Пока рассмотрим только синтаксис, а остальные особенности чуть позже.
*Хабр не умеет подсвечивать YAML, так что пришлось разместить картинки
Как вам? Мне на первый взгляд показалось, что очень похоже на Python, но с какими-то опечатками.
Рассмотрим синтаксис подробнее.
Концепции, типы, синтаксис
Отступы
В YAML для разделения информации очень важны отступы. Нужно помнить, что используются только пробелы, табы не допускаются.
При отсутствии отступа перед первым объявлением YAML поймет, что это корень (уровень 0) вашего файла.
Если вы привыкли использовать tab-ы вместо пробелов, то можно использовать какой-нибудь плагин в вашей IDE, чтобы заменить все пропуски на пробелы (например, editorconfig).
Ключ/Значение
Как и в JSON/JS, в YAML есть синтаксис ключ/значение, и вы можете использовать его различными способами:
Комментарии
Чтобы написать комментарий, вы можете использовать #, а затем ваше сообщение.
Это круто, когда нужно задокументировать какое-то решение или сделать заметку в конфиге. К сожалению, мы не можем так сделать в JSON.
Списки
В YAML есть 2 способа написания списков:
Помните, что YAML — это расширенный JSON? Поэтому мы можем использовать его синтаксис
Наиболее распространенный и рекомендуемый
Числа
Тут все стандартно: целые числа и числа с плавающей точкой.
Строки
Есть несколько способов объявить строку в YAML:
Если вы хотите использовать какой-нибудь специальный символ, например, _ или @, то нужны будут кавычки.
Напомню, что в JSON у нас есть только один способ написания строк — двойные кавычки.
И главная фишка…
Якорь (переменная или ссылка)
Якорь — это механизм для создания переменных, на которые затем можно ссылаться.
Давайте представим, что вам нужно создать конфигурацию для вашего CI. Он будет иметь версию для production и development сред. Обе версии будут иметь почти одинаковые базовые настройки.
В JSON нам пришлось бы дублировать эти конфиги:
Копирование и вставка очень раздражают, особенно когда нужно что-то изменить во всех местах.
Якорь решает эту проблему. Для его создания используется символ якоря (&), а для вставки — алиас (*).
Рис.2. Отсылка к фильму «Матрица»
Возможности YAML-а покоряют при его сравнении с JSON. Но если у вас довольно простой конфиг в пару-тройку строк, то нет смысла усложнять и использовать дополнительные возможности YAML, лучше выбрать JSON. А если же у вас довольно большой и витиеватый файл, то тут однозначно стоит рассмотреть YAML.
У YAML есть еще несколько интересных фишек таких как: многострочный ввод, мерж блоков, матрицы, наследование и другие.
Так как YAML — это расширенный JSON, то мы можем писать YAML-файл в JSON-формате, и он будет работать. Это отличная особенность, которая позволит легче начать изучение YAML.
YAML vs JSON – Which is better?
Nowadays, almost every person is familiar with the standard format of JSON. Contrarily, individuals who use Docker are surely familiar with YAML. In simpler words, Docker is a toolkit which permits developers to run, build, deploy, modify as well as stop packages through a single API or commands. YAML is a new but popular language used to serialize data. First of all, we should perceive what data serialization is. Data serialization is the most common way of transforming data objects into byte streams used to store, transfer and distribute data on devices. However, they have similar objectives to store structures and data objects into files but distinctive ways to work.
In this article, we first go through the features of JSON and YAML, then compare them in-depth to completely comprehend their advantages, and then briefly discuss which one is better.
YAML is an abbreviation of Yet Another Markup Language and is used to define configurations. It is lightweight and represents data in a human-readable format. If you want to parse JSON then you have to use the YAML parser as JSON is a subset of YAML. Moreover, JSON can be converted into YAML. YAML also has JSON in its configuration files. YAML not only permits user-defined data types but also allows explicit data typing. “.YML” or “.YAML” are extensions of YAML. Here is the link to its official documentation https://yaml.org/. YAML differs from JSON as it uses Python-like indentations to represent levels in data. In YAML, lists start with hyphens and key pairs can be separated with a colon. Three dashes (“—”) indicate the beginning of a document whereas three dots (“…”) indicate the end of a document.
Example
Below is the example to show the YAML format. This example contains information about various cars.
First of all, we quickly define what JSON is. JSON depends on the JavaScript language. JSON can be used with any programming language as it is not language independent but mostly used with JavaScript. It stores data in a standard format. In JSON, records can be separated through commas whereas strings and fields are enclosed within double quotes (“ ”).
Example
Below is the example to show the JSON format. This example stores information related to cars.
YAML VS JSON:
YAML and JSON are not as simple to compare as you think. If we talk about the readability of data from configuration files then both JSON and YAML can be used interchangeably. Therefore, the comparison is quite difficult in terms of readability. In the configuration file, JSON might be able to express the same data types just like YAML. Although YAML is a set of key/value pairs, there is no object in it.
Moreover, JSON is a full-fledged data structure used extensively for storing data in programming languages like JavaScript. On the other hand, YAML is not present outside the configuration file.
JSON is best suited in terms of serialization format whereas YAML is better as a configuration. JSON has a serialization format that has originated from JavaScript objects
In JSON, strings can be used in double-quotes whereas YAML supports both single and double-quotes. Comments are not allowed in JSON while comments are represented through hash or number signs in YAML.
Conclusion
It is quite difficult to decide whether JSON is better or YAML. Therefore, I have decided to compare these with different aspects. When you talk about readability, YAML is much better, but moving towards the size then JSON takes the edge. JSON is comparatively faster than YAML. However, if data configurations are small then YAML is better since its interface is much more friendly.
JSON has a feature to encode six different data types like an object, array, strings, numbers, null and boolean. JSON is much easier for machines to parse and it is quite flexible compared to YAML which allows encoding of python data but with vulnerabilities while decoding. That’s why YAML is too hard to parse.
YAML vs. JSON: What is the difference?
JSON and YAML are two popular formats for data exchange between different applications and languages, also known as data serialization.
They’re similar in function and features: they represent data objects and structures and use a simple syntax that facilitates readability and editability.
But differences in design affect their scope of use. This overview of YAML and JSON will show their main features and compare them to help you make the right choice for your project.
Table of contents
What is JSON
JSON means JavaScript Object Notation. As you might suspect by the name, JSON derives from JavaScript data formats. It is an open standard, lightweight, text-based format with limited data types. Its short syntax and simple structure make it very easy to read.
It’s used to send data to the server and from server to client, like an envelope in which the data is enclosed and sent back and forward between correspondents.
It’s highly appreciated by programmers who use it in mobile apps, database services like MongoDB or Kubernetes, and user interactions, being a more user-friendly alternative to XML. The simplicity and speed of processing that JSON offers and its high compatibility with any system make it one of the most popular formats in use today.
The JSON History
According to JSON’s developer, Douglas Crockford, a language using the same principles was already being used at Netscape in 1996, but JSON only became mainstream as an established syntax in 2001.
It is a go-to resource for Android technology, REST-API, or any situation where data is sent from a server to a web page. It is language-independent, which means it can be used with any programming language. And a huge part of our online experience relies on it.
Tech specs
“An object is an unordered set of name/value pairs. An object begins with
and ends with >right brace. Each name is followed by :colon, and the name/value pairs are separated by ,comma.”
Data types used by JSON
Syntax
JSON’s syntax rules are simple.
JSON Example
Let’s look at a JSON example, using some information about the famous heavy metal band Metallica.
As you can see, curly brackets delimit both the object and the arrays. All items are quoted, and the attribute name is separated from the value by a colon. A comma is used to separate name:value pairings.
Lists are defined by using square brackets, where the array attributes are also separated by commas.
Advantages of JSON
Disadvantages of JSON
What is YAML
YAML used to mean Yet Another Markup Language, but that meaning changed to YAML Ain’t Markup Language to express its data focus over a document focus. Acronyms aside, YAML is a very human-readable, lightweight format, commonly used to store configuration information for DevOps tools like ElasticSearch, Docker, Kubernetes, Prometheus, and Ansible.
Like it says on the official website, also written in YAML format:
“YAML is a human-friendly data serialization language for all programming languages.”
It is a data serialization language, but it is also often used for writing configuration files. We’ll be looking at YAML through the data serialization prism.
The YAML History
YAML was first publicized in 2001. The founding members of YAML are IngydotNet, Clark Evans, and Oren Ben-Kiki, who joined efforts to create a simpler format than XML. You can read the story from a firsthand perspective. Since then, it has become a workhorse for developers everywhere.
Tech specs
YAML is written in a very clear human-readable format, with the added advantage of supporting comments, making it super easy to edit. Since it is a superset of JSON, a valid YAML file can contain JSON objects. It is suited to support complex data types, with the ability to enclose multi-level objects. This makes it less friendly to use with some technologies.
Data types
YAML accepts the same data types as JSON, the main difference being the ability to support date attributes.
Syntax
The absence of brackets and quotes for most of the functions makes the reading more natural. Even the uninitiated get a quick understanding of what is supposed to happen. YAML’s syntax is its strength but also a source for validation problems if we don’t pay attention to indents and space positions.
YAML Example
Now, see how the same data we used above for JSON looks in YAML format:
On a first impression, YAML looks better than JSON since it gets rid of all the brackets and quotes. It doesn’t read much like code but more as an outline.
Advantages of YAML
Disadvantages of YAML
Differences between JSON and YAML
YAML and JSON are two popular languages, similar in structure and usability. Their differences in design, syntax, and functionality make the choice between them a matter of purpose.
JSON | YAML |