How is the yaml data format structure different from json

How is the yaml data format structure different from json

Yaml vs. Json — что круче?

How is the yaml data format structure different from json. Смотреть фото How is the yaml data format structure different from json. Смотреть картинку How is the yaml data format structure different from json. Картинка про How is the yaml data format structure different from json. Фото How is the yaml data format structure different from json

Сегодня поговорим об интересном (и таинственном для фронтов) формате YAML. Он считается одним из наиболее популярных форматов для файлов конфигураций.

Цель этой статьи — познакомить вас со структурой YAML, помочь понимать, читать и изменять YAML-файлы. Для тех, кто уже знаком с форматом — напомнить про некоторые его особенности. И сравнить YAML с JSON.

Цели создания

Сообщество разработчиков устало от «зоопарка» различных форматов для конфигов, им хотелось упростить себе жизнь и прийти к единому понятному формату. И в 2001 году Кларк Эванс создал YAML 1.0.

Его основные цели:

How is the yaml data format structure different from json. Смотреть фото How is the yaml data format structure different from json. Смотреть картинку How is the yaml data format structure different from json. Картинка про How is the yaml data format structure different from json. Фото How is the yaml data format structure different from json
Рис.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, так что пришлось разместить картинки
How is the yaml data format structure different from json. Смотреть фото How is the yaml data format structure different from json. Смотреть картинку How is the yaml data format structure different from json. Картинка про How is the yaml data format structure different from json. Фото How is the yaml data format structure different from json

Как вам? Мне на первый взгляд показалось, что очень похоже на Python, но с какими-то опечатками.

Рассмотрим синтаксис подробнее.

Концепции, типы, синтаксис

Отступы

В YAML для разделения информации очень важны отступы. Нужно помнить, что используются только пробелы, табы не допускаются.

При отсутствии отступа перед первым объявлением YAML поймет, что это корень (уровень 0) вашего файла.

Если вы привыкли использовать tab-ы вместо пробелов, то можно использовать какой-нибудь плагин в вашей IDE, чтобы заменить все пропуски на пробелы (например, editorconfig).

Ключ/Значение

Как и в JSON/JS, в YAML есть синтаксис ключ/значение, и вы можете использовать его различными способами:

How is the yaml data format structure different from json. Смотреть фото How is the yaml data format structure different from json. Смотреть картинку How is the yaml data format structure different from json. Картинка про How is the yaml data format structure different from json. Фото How is the yaml data format structure different from json

Комментарии

Чтобы написать комментарий, вы можете использовать #, а затем ваше сообщение.

How is the yaml data format structure different from json. Смотреть фото How is the yaml data format structure different from json. Смотреть картинку How is the yaml data format structure different from json. Картинка про How is the yaml data format structure different from json. Фото How is the yaml data format structure different from json

Это круто, когда нужно задокументировать какое-то решение или сделать заметку в конфиге. К сожалению, мы не можем так сделать в JSON.

Списки

В YAML есть 2 способа написания списков:

Помните, что YAML — это расширенный JSON? Поэтому мы можем использовать его синтаксис

Наиболее распространенный и рекомендуемый

Числа

Тут все стандартно: целые числа и числа с плавающей точкой.

How is the yaml data format structure different from json. Смотреть фото How is the yaml data format structure different from json. Смотреть картинку How is the yaml data format structure different from json. Картинка про How is the yaml data format structure different from json. Фото How is the yaml data format structure different from json

Строки

Есть несколько способов объявить строку в YAML:

How is the yaml data format structure different from json. Смотреть фото How is the yaml data format structure different from json. Смотреть картинку How is the yaml data format structure different from json. Картинка про How is the yaml data format structure different from json. Фото How is the yaml data format structure different from json

Если вы хотите использовать какой-нибудь специальный символ, например, _ или @, то нужны будут кавычки.

Напомню, что в JSON у нас есть только один способ написания строк — двойные кавычки.

И главная фишка…

Якорь (переменная или ссылка)

Якорь — это механизм для создания переменных, на которые затем можно ссылаться.

Давайте представим, что вам нужно создать конфигурацию для вашего CI. Он будет иметь версию для production и development сред. Обе версии будут иметь почти одинаковые базовые настройки.

В JSON нам пришлось бы дублировать эти конфиги:

Копирование и вставка очень раздражают, особенно когда нужно что-то изменить во всех местах.

Якорь решает эту проблему. Для его создания используется символ якоря (&), а для вставки — алиас (*).

How is the yaml data format structure different from json. Смотреть фото How is the yaml data format structure different from json. Смотреть картинку How is the yaml data format structure different from json. Картинка про How is the yaml data format structure different from json. Фото How is the yaml data format structure different from json

How is the yaml data format structure different from json. Смотреть фото How is the yaml data format structure different from json. Смотреть картинку How is the yaml data format structure different from json. Картинка про How is the yaml data format structure different from json. Фото How is the yaml data format structure different from 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?

How is the yaml data format structure different from json. Смотреть фото How is the yaml data format structure different from json. Смотреть картинку How is the yaml data format structure different from json. Картинка про How is the yaml data format structure different from json. Фото How is the yaml data format structure different from json

How is the yaml data format structure different from json. Смотреть фото How is the yaml data format structure different from json. Смотреть картинку How is the yaml data format structure different from json. Картинка про How is the yaml data format structure different from json. Фото How is the yaml data format structure different from json

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.

Syntax

Easy to read, though with brackets, commas, and quotes.

Easier to read than JSON, but sometimes leading to misinterpretations in attribute values.

Hierarchy

Supports simple hierarchy through associative arrays and lists.

Natively supports object references and relational trees.

Complexity

Simple data types and structure.

Possibility to have complex data structures with more complex data types available.

Performance

Faster generation and parsing.

More complex data structures slow down parsing.

Support

Active, engaged community, many available libraries.

Smaller community than JSON, which means fewer libraries and support.

Functionality

It has fewer native features than YAML, which curbs data serialization complexity.

More interesting for complex data serialization.

YAML or JSON: Which is better?

When choosing between JSON or YAML format, just follow function: what do you need them to do?

JSON has a faster delivery since it works perfectly as a simple data exchange format. But it is limited to the supported data types, which can require extra resources to deal with data sets with a larger number of data type options. It is easy to read once you’re over the brackets and quotes, which is an advantage since they delimit specific items, reducing the risk of parsing misinterpretation.

YAML, on the other hand, almost doesn’t read like code. And the matryoshka-like ability to include objects within objects allows for greater data complexity. The downside? Such complexity slows down the parsing and generation process. But with a range of complex data types available, it has its appeal and is a great option to expand the types of information to be made available.

The purpose and priority of the information to deliver are also important, and a logical hierarchy should be defined before starting coding. This prior organization will define the structure of the document and how data will be presented.

No matter the choice, it’s all about what your data is supposed to do in the end.

Want more tips and tricks from our professionals? Subscribe here and stay up to date with the latest trends!

How is the yaml data format structure different from json. Смотреть фото How is the yaml data format structure different from json. Смотреть картинку How is the yaml data format structure different from json. Картинка про How is the yaml data format structure different from json. Фото How is the yaml data format structure different from json

Found this article useful? You might like these ones too!

At Imaginary Cloud, we simplify complex systems, delivering interfaces that users love. If you’ve enjoyed this article, you will certainly enjoy our newsletter, which may be subscribed below. Take this chance to also check our latest work and, if there is any project that you think we can help with, feel free to reach us. We look forward to hearing from you!

Alex Gamela

Content writer and digital media producer with an interest in the symbiotic relationship between tech and society. Books, music, and guitars are a constant.

What is the difference between YAML and JSON?

What are the differences between YAML and JSON, specifically considering the following things?

I was planning to use one of these two in our embedded system to store configure files.

Related:

How is the yaml data format structure different from json. Смотреть фото How is the yaml data format structure different from json. Смотреть картинку How is the yaml data format structure different from json. Картинка про How is the yaml data format structure different from json. Фото How is the yaml data format structure different from json

14 Answers 14

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Technically YAML is a superset of JSON. This means that, in theory at least, a YAML parser can understand JSON, but not necessarily the other way around.

See the official specs, in the section entitled «YAML: Relation to JSON».

In general, there are certain things I like about YAML that are not available in JSON.

In practice neither of these last two points will likely matter for things that you or I do, but in the long term, I think YAML will be a more robust and viable data serialization format.

Right now, AJAX and other web technologies tend to use JSON. YAML is currently being used more for offline data processes. For example, it is included by default in the C-based OpenCV computer vision package, whereas JSON is not.

You will find C libraries for both JSON and YAML. YAML’s libraries tend to be newer, but I have had no trouble with them in the past. See for example Yaml-cpp.

Bypassing esoteric theory

This answers the title, not the details as most just read the title from a search result on google like me so I felt it was necessary to explain from a web developer perspective.

The Elephant in the room: The Internet itself

JavaScript so clearly dominates the web by a huge margin and JavaScript developers prefer using JSON as the data format overwhelmingly along with popular web APIs so it becomes difficult to argue using YAML over JSON when doing web programming in the general sense as you will likely be outvoted in a team environment. In fact, the majority of web programmers aren’t even aware YAML exists, let alone consider using it.

If you are doing any web programming, JSON is the default way to go because no translation step is needed when working with JavaScript so then you must come up with a better argument to use YAML over JSON in that case.

JSON vs YAML

A dive into two popular data serialization languages

Any person with an interest in programming and technology knows what JSON is. YAML is not as common as JSON, but it is also a popular and awesome data serialization language. For example, any person who has used docker surely knows what YAML is.

First of all, let’s see what is meant by data serialization. According to Devopedia data serialization is the process of converting data objects present in complex data structures into a byte stream for storage, transfer, and distribution purposes on physical devices. So JSON and YAML both are a way of storing the data objects and structures in files.

What is JSON?

Although most of us know what JSON is, let’s have a quick introduction. JSON is the short name for JavaScript Object Notation. JSON is based on a subset of JavaScript programming language standard ECMA-262 3rd Edition-December 1999. JSON is widely used with JavaScript but since it is language-independent, it can be used with any programming language.

JSON has a standard format for data storing. It stores data in key/value pairs. The records are separated by commas and both field names and strings are enclosed with double-quotes.

How is the yaml data format structure different from json. Смотреть фото How is the yaml data format structure different from json. Смотреть картинку How is the yaml data format structure different from json. Картинка про How is the yaml data format structure different from json. Фото How is the yaml data format structure different from json

Here, “title” is a key, and “The first element” is a value. “elements” key contains an array of element objects and the “content” key contains a data object.

What is YAML?

YAML is the short name for YAML Ain’t Markup Language. And YAML Ain’t Markup Language is the short name for YAML ain’t markup language ain’t markup language. Pretty cool right. To make things more interesting, the official YAML website is also displayed in YAML format.

How is the yaml data format structure different from json. Смотреть фото How is the yaml data format structure different from json. Смотреть картинку How is the yaml data format structure different from json. Картинка про How is the yaml data format structure different from json. Фото How is the yaml data format structure different from json

Here, first_name is a key and Adam is a value. spouse points to a data object with name, occupation, interests as children and interests is an array of data.

Pros & Cons — JSON vs YAML

Theoretically, both JSON and YAML are expected to perform the same task. That is providing a human-readable data interchange format.

How is the yaml data format structure different from json. Смотреть фото How is the yaml data format structure different from json. Смотреть картинку How is the yaml data format structure different from json. Картинка про How is the yaml data format structure different from json. Фото How is the yaml data format structure different from json

The design goal of JSON is to be simpler as possible and be universally usable. So this has reduced the readability of the data up to some extent. In contrast, the design goal of YAML is to provide a good human-readable format and provide support for serializing arbitrary native data structures. So this has increased the readability of the YAML files but it has made the parsing and generation of files somewhat complex. We can see this clearly in the YAML official website where it shows the content in YAML format and it is easily readable for anyone visiting the site. On the other hand, if it was displayed in JSON format, the webpage would be useless.

It is said that YAML is a superset of JSON format. What is simply meant by this is that we can parse JSON using a YAML parser. However, in practical scenarios, this parsing may rise problems, but it is theoretically possible.

In the data serialization contest, JSON is the winner because of the ability to quickly and easily parse JSON serialized data with its simpler design. And this has made JSON more popular among developers which results in more and more native support and this has improved the performance more again. Therefore JSON has become the most widely used data interchange format for web applications and web services.

For any programming language, we can easily find a JSON library integrated with the language due to its popularity, it’s ease use of implementation and it’s simplicity. The JSON official website lists many languages with many supporting libraries for JSON. YAML also has widespread support and many libraries for integrating it with various languages, but not as much as JSON. You can get the list of libraries and languages that support YAML here.

So far we discussed the pros of JSON over YAML. But some considerably important features of YAML is not found with JSON. YAML supports comments where JSON does not. We can comment anywhere in the document with a simple # character. This has proven advantageous when writing configuration files where one developer can easily describe the configuration using the comments. Therefore YAML format is used in many technology stacks like ElasticSearch, Docker for storing configuration information.

Ability to use Complex Structures

Another feature that YAML provides is the ability to reference other data objects. With this referencing, it is possible to write recursive data in the YAML file.

How is the yaml data format structure different from json. Смотреть фото How is the yaml data format structure different from json. Смотреть картинку How is the yaml data format structure different from json. Картинка про How is the yaml data format structure different from json. Фото How is the yaml data format structure different from json

For this, we can define Anchors in the YAML file using “ &” and refer to them later using Aliases, “ *”. This is a very important feature in YAML that JSON does not offer. In JSON, it is impossible to serialize complex structures with object references. But the above feature in YAML solves that problem. But one drawback of this is the possibility of infinite looping in some converters.

So from all these points, we can see that both JSON and YAML have their strengths and their weaknesses. A good developer should be able to identify these and use the correct format in the correct place.

I hope you got something from my article. Hope to bring more articles soon. And thank you for reading. Cheers.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

JSONYAML