YAML 和 JSON 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1726802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:21:41  来源:igfitidea点击:

What is the difference between YAML and JSON?

jsonyaml

提问by pierrotlefou

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

YAML 和 JSON 有什么区别,具体考虑以下几点?

  • Performance (encode/decode time)
  • Memory consumption
  • Expression clarity
  • Library availability, ease of use (I prefer C)
  • 性能(编码/解码时间)
  • 内存消耗
  • 表达清晰
  • 库可用性、易用性(我更喜欢 C)

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

我计划在我们的嵌入式系统中使用这两个中的一个来存储配置文件。

Related:

有关的:

Should I use YAML or JSON to store my Perl data?

我应该使用 YAML 还是 JSON 来存储我的 Perl 数据?

采纳答案by AndyL

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.

从技术上讲,YAML 是 JSON 的超集。这意味着,至少在理论上,YAML 解析器可以理解 JSON,但反过来不一定。

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

请参阅标题为“YAML:与 JSON 的关系”部分中的官方规范。

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

总的来说,我喜欢 YAML 的某些方面,但在 JSON 中是不可用的。

  • As @jdupont pointed out, YAML is visually easier to look at. In fact the YAML homepageis itself valid YAML, yet it is easy for a human to read.
  • YAML has the ability to reference other items within a YAML file using "anchors." Thus it can handle relational information as one might find in a MySQL database.
  • YAML is more robust about embedding other serialization formats such as JSON or XML withina YAML file.
  • 正如@jdupont 指出的那样,YAML 在视觉上更易于查看。事实上,YAML 主页本身就是有效的 YAML,但它很容易被人类阅读。
  • YAML 能够使用“锚点”引用 YAML 文件中的其他项目。因此,它可以像在 MySQL 数据库中找到的那样处理关系信息。
  • YAML是有关嵌入其他序列化格式诸如JSON或XML更健壮的YAML文件。

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.

在实践中,最后两点对你我所做的事情都不重要,但从长远来看,我认为 YAML 将是一种更健壮和可行的数据序列化格式。

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.

目前,AJAX 和其他 Web 技术倾向于使用 JSON。YAML 目前更多地用于离线数据处理。例如,它默认包含在基于 C 的 OpenCV 计算机视觉包中,而 JSON 则不包含。

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.

您将找到适用于 JSON 和 YAML 的 C 库。YAML 的库往往更新,但我过去没有遇到过这些问题。参见例如Yaml-cpp

回答by Erik Aronesty

Differences:

区别:

  1. YAML, depending on how you use it, can be more readable than JSON
  2. JSON is often fasterand is probably still interoperable with more systems
  3. It's possible to write a "good enough" JSON parser very quickly
  4. Duplicate keys, which are potentiallyvalid JSON, are definitelyinvalid YAML.
  5. YAML has a ton of features, including comments and relational anchors. YAML syntax is accordingly quite complex, and can be hard to understand.
  6. It is possible to write recursive structures in yaml: {a: &b [*b]}, which will loop infinitely in some converters. Even with circular detection, a "yaml bomb" is still possible (see xml bomb).
  7. Because there are no references, it is impossible to serialize complex structures with object references in JSON. YAML serialization can therefore be more efficient.
  8. In some coding environments, the use of YAML can allow an attacker to execute arbitrary code.
  1. YAML,取决于你如何使用它,可能比 JSON 更具可读性
  2. JSON 通常更快,并且可能仍可与更多系统互操作
  3. 可以很快地编写一个“足够好”的 JSON 解析器
  4. 重复键,这是潜在的有效的JSON,是绝对无效YAML。
  5. YAML 具有大量功能,包括注释和关系锚点。YAML 语法因此非常复杂,并且可能难以理解。
  6. 可以在 yaml: 中编写递归结构{a: &b [*b]},这将在某些转换器中无限循环。即使使用循环检测,“yaml 炸弹”仍然是可能的(请参阅xml 炸弹)。
  7. 因为没有引用,所以不可能用 JSON 中的对象引用序列化复杂的结构。因此,YAML 序列化可以更高效。
  8. 在某些编码环境中,使用 YAML 可以允许攻击者执行任意代码

Observations:

观察:

  1. Python programmers are generally big fans of YAML, because of the use of indentation, rather than bracketed syntax, to indicate levels.
  2. Many programmers consider the attachment of "meaning" to indentation a poor choice.
  3. If the data format will be leaving an application's environment, parsed within a UI, or sent in a messaging layer, JSON might be a better choice.
  4. YAML can be used, directly, for complex tasks like grammar definitions, and is often a better choice than inventing a new language.
  1. Python 程序员通常是 YAML 的忠实粉丝,因为使用缩进而不是括号语法来表示级别。
  2. 许多程序员认为将“意义”附加到缩进是一个糟糕的选择。
  3. 如果数据格式将离开应用程序环境、在 UI 中解析或在消息传递层中发送,则 JSON 可能是更好的选择。
  4. YAML 可以直接用于语法定义等复杂任务,并且通常是比发明一种新语言更好的选择。

回答by Jason Sebring

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.

这回答了标题,而不是细节,因为大多数人只是像我一样从 google 上的搜索结果中阅读标题,所以我觉得有必要从 Web 开发人员的角度进行解释。

  1. YAML uses space indentation, which is familiar territory for Python developers.
  2. JavaScript developers love JSON because it is a subset of JavaScript and can be directly interpreted and written inside JavaScript, along with using a shorthand way to declare JSON, requiring no double quotes in keys when using typical variable names without spaces.
  3. There are a plethora of parsers that work very well in all languages for both YAML and JSON.
  4. YAML's space format can be much easier to look at in many cases because the formatting requires a more human-readable approach.
  5. YAML's form while being more compact and easier to look at can be deceptively difficult to hand edit if you don't have space formatting visible in your editor. Tabs are not spaces so that further confuses if you don't have an editor to interpret your keystrokes into spaces.
  6. JSON is much faster to serialize and deserialize because of significantly less features than YAML to check for, which enables smaller and lighter code to process JSON.
  7. A common misconceptionis that YAML needs less punctuation and is more compact than JSON but this is completely false. Whitespace is invisible so it seems like there are less characters, but if you count the actual whitespace which is necessary to be there for YAML to be interpreted properly along with proper indentation, you will find YAML actually requires more characters than JSON. JSON doesn't use whitespace to represent hierarchy or grouping and can be easily flattened with unnecessary whitespace removed for more compact transport.
  1. YAML 使用空格缩进,这是 Python 开发人员熟悉的领域。
  2. JavaScript 开发人员喜欢 JSON,因为它是 JavaScript 的一个子集,可以直接在 JavaScript 中解释和编写,同时使用速记方式来声明 JSON,在使用典型的不带空格的变量名时不需要在键中使用双引号。
  3. 有大量的解析器在 YAML 和 JSON 的所有语言中都能很好地工作。
  4. 在许多情况下,YAML 的空间格式更容易查看,因为格式设置需要更易读的方法。
  5. 如果您的编辑器中没有可见的空格格式,那么 YAML 的形式虽然更紧凑且更易于查看,但可能很难手动编辑。制表符不是空格,因此如果您没有编辑器将您的击键解释为空格,则会进一步混淆。
  6. JSON 序列化和反序列化的速度要快得多,因为要检查的功能比 YAML 少得多,这使得处理 JSON 的代码更小、更轻。
  7. 一个常见的误解是 YAML 需要更少的标点符号并且比 JSON 更紧凑,但这是完全错误的。空格是不可见的,因此似乎字符较少,但是如果您计算 YAML 被正确解释以及正确缩进所必需的实际空格,您会发现 YAML 实际上需要比 JSON 更多的字符。JSON 不使用空格来表示层次结构或分组,并且可以通过移除不必要的空格来轻松展平,以实现更紧凑的传输。

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.

JavaScript 显然以巨大的优势主导了 Web,JavaScript 开发人员更喜欢使用 JSON 作为数据格式以及流行的 Web API,因此在一般意义上进行 Web 编程时,很难争论使用 YAML 而非 JSON,因为您可能会被否决在团队环境中。事实上,大多数 Web 程序员甚至都不知道 YAML 的存在,更不用说考虑使用它了。

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.

如果您正在进行任何 Web 编程,JSON 是默认方式,因为在使用 JavaScript 时不需要翻译步骤,因此在这种情况下,您必须提出一个更好的参数来使用 YAML 而不是 JSON。

回答by Steve Bennett

This question is 6 years old, but strangely, none of the answers really addresses all four points (speed, memory, expressiveness, portability).

这个问题已经有 6 年历史了,但奇怪的是,没有一个答案真正解决了所有四点(速度、记忆力、表现力、便携性)。

Speed

速度

Obviously this is implementation-dependent, but because JSON is so widely used, and so easy to implement, it has tended to receive greater native support, and hence speed. Considering that YAML does everything that JSON does, plus a truckload more, it's likely that of any comparable implementations of both, the JSON one will be quicker.

显然,这是依赖于实现的,但由于 JSON 使用如此广泛,而且易于实现,因此它倾向于获得更多的本机支持,因此速度更快。考虑到 YAML 可以完成 JSON 所做的一切,再加上一卡车的装载量,很可能在两者的任何可比实现中,JSON 会更快。

However, given that a YAML file can be slightly smaller than its JSON counterpart (due to fewer "and ,characters), it's possiblethat a highly optimised YAML parser might be quicker in exceptional circumstances.

然而,考虑到YAML文件可以比其对应的JSON(由于较少略小",字符),它可能是一个高度优化的YAML解析器可能会更快在特殊情况下。

Memory

记忆

Basically the same argument applies. It's hard to see why a YAML parser would ever be more memory efficient than a JSON parser, if they're representing the same data structure.

基本上相同的论点适用。如果 YAML 解析器表示相同的数据结构,那么很难理解为什么 YAML 解析器比 JSON 解析器的内存效率更高。

Expressiveness

表现力

As noted by others, Python programmers tend towards preferring YAML, JavaScript programmers towards JSON. I'll make these observations:

正如其他人所指出的,Python 程序员倾向于使用 YAML,JavaScript 程序员倾向于使用 JSON。我将进行以下观察:

  • It's easy to memorise the entire syntax of JSON, and hence be very confident about understanding the meaning of any JSON file. YAML is not truly understandable by any human. The number of subtleties and edge cases is extreme.
  • Because few parsers implement the entire spec, it's even harder to be certain about the meaning of a given expression in a given context.
  • The lack of comments in JSON is, in practice, a real pain.
  • 记住 JSON 的整个语法很容易,因此对理解任何 JSON 文件的含义非常有信心。任何人都无法真正理解 YAML。微妙之处和边缘情况的数量是极端的。
  • 因为很少有解析器实现整个规范,所以更难确定给定上下文中给定表达式的含义。
  • 在实践中,JSON 中缺少注释是一个真正的痛苦。

Portability

可移植性

It's hard to imagine a modern language without a JSON library. It's also hard to imagine a JSON parser implementing anything less than the full spec. YAML has widespread support, but is less ubiquitous than JSON, and each parser implements a different subset. Hence YAML files are less interoperable than you might think.

很难想象没有 JSON 库的现代语言。也很难想象一个 JSON 解析器实现了任何不完整规范的东西。YAML 得到了广泛的支持,但不如 JSON 普遍,而且每个解析器都实现了不同的子集。因此,YAML 文件的互操作性比您想象的要差。

Summary

概括

JSON is the winner for performance (if relevant) and interoperability. YAML is better for human-maintained files. HJSONis a decent compromise although with much reduced portability. JSON5is a more reasonable compromise, with well-defined syntax.

JSON 是性能(如果相关)和互操作性的赢家。YAML 更适合人工维护的文件。HJSON是一个不错的折衷方案,尽管可移植性大大降低。JSON5是一种更合理的折衷方案,具有明确定义的语法。

回答by JohnAD

GIT and YAML

GIT 和 YAML

The other answers are good. Read those first. But I'll add one other reason to use YAML sometimes: git.

其他答案都很好。先读那些。但有时我会添加另一个使用 YAML 的原因:git

Increasingly, many programming projects use git repositories for distribution and archival. And, while a git repo's history can equally store JSON and YAML files, the "diff" method used for tracking and displaying changes to a file is line-oriented. Since YAML is forced to be line-oriented, any small changes in a YAML file are easier to see by a human.

越来越多的编程项目使用 git 存储库进行分发和存档。而且,虽然 git repo 的历史记录可以同等地存储 JSON 和 YAML 文件,但用于跟踪和显示文件更改的“diff”方法是面向行的。由于 YAML 被迫面向行,因此 YAML 文件中的任何小更改都更容易被人类看到。

It is true, of course, that JSON files can be "made pretty" by sorting the strings/keys and adding indentation. But this is not the default and I'm lazy.

当然,确实可以通过对字符串/键进行排序并添加缩进来“使 JSON 文件变得漂亮”。但这不是默认设置,我很懒。

Personally, I generally use JSON for system-to-system interaction. I often use YAML for config files, static files, and tracked files. (I also generally avoid adding YAML relational anchors. Life is too short to hunt down loops.)

就我个人而言,我通常使用 JSON 进行系统到系统的交互。我经常将 YAML 用于配置文件、静态文件和跟踪文件。(我通常也避免添加 YAML 关系锚点。生命太短暂,无法追捕循环。)

Also, if speed and space are really a concern, I don't use either. You might want to look at BSON.

此外,如果速度和空间真的很重要,我也不使用。你可能想看看 BSON。

回答by jldupont

I find YAML to be easier on the eyes: less parenthesis, "" etc. Although there is the annoyance of tabs in YAML... but one gets the hang of it.

我发现 YAML 看起来更容易:少括号、"" 等。虽然 YAML 中的选项卡令人烦恼......但人们已经掌握了它的窍门。

In terms of performance/resources, I wouldn't expect big differences between the two.

在性能/资源方面,我预计两者之间不会有太大差异。

Futhermore, we are talking about configuration files and so I wouldn't expect a high frequency of encode/decode activity, no?

此外,我们正在谈论配置文件,所以我不希望编码/解码活动的频率很高,不是吗?

回答by jldupont

If you don't need any features which YAML has and JSON doesn't, I would prefer JSON because it is very simple and is widely supported (has a lot of libraries in many languages). YAML is more complex and has less support. I don't think the parsing speed or memory use will be very much different, and maybe not a big part of your program's performance.

如果您不需要 YAML 具有而 JSON 没有的任何功能,我会更喜欢 JSON,因为它非常简单并且得到广泛支持(有很多语言的库)。YAML 更复杂,支持更少。我不认为解析速度或内存使用会有很大不同,而且可能不是程序性能的重要组成部分。

回答by Wernight

Technically YAMLoffers a lot more than JSON(YAML v1.2 is a superset of JSON):

从技术上讲,YAML提供的不仅仅是JSON(YAML v1.2 是 JSON 的超集):

  • comments
  • anchors and inheritance - example of 3 identical items:

    item1: &anchor_name
      name: Test
      title: Test title
    item2: *anchor_name
    item3:
      <<: *anchor_name
      # You may add extra stuff.
    
  • ...
  • 注释
  • 锚点和继承 - 3 个相同项目的示例:

    item1: &anchor_name
      name: Test
      title: Test title
    item2: *anchor_name
    item3:
      <<: *anchor_name
      # You may add extra stuff.
    
  • ...

Most of the time people will not use those extra features and the main difference is that YAML uses indentationwhilst JSON uses brackets. This makes YAML more concise and readable(for the trained eye).

大多数时候人们不会使用这些额外的功能,主要区别在于YAML 使用缩进JSON 使用括号。这使得 YAML 更加简洁和可读(对于训练有素的眼睛)。

Which one to choose?

选择哪一个?

  • YAMLextra features and concise notation makes it a good choice for configuration files(non-user provided files).
  • JSONlimited features, wide support, and faster parsing makes it a great choice for interoperability and user provided data.
  • YAML额外的功能和简洁的符号使其成为配置文件(非用户提供的文件)的不错选择。
  • JSON有限的功能、广泛的支持和更快的解析使其成为互操作性和用户提供数据的绝佳选择。

回答by Mvr39

Since this question now features prominently when searching for YAML and JSON, it's worth noting one rarely-cited difference between the two: license. JSON purports to have a licensewhich JSON users must adhere to (including the legally-ambiguous "shall be used for Good, not Evil"). YAML carries no such license claim, and that might be an important difference (to your lawyer, if not to you).

由于这个问题现在在搜索 YAML 和 JSON 时占据突出地位,因此值得注意的是两者之间一个很少被引用的区别:许可证。JSON 声称拥有JSON 用户必须遵守的许可证(包括法律上模棱两可的“应用于善,而不是恶”)。YAML 没有此类许可声明,这可能是一个重要的区别(对您的律师而言,如果不是对您而言)。

回答by Michael Dorner

Sometimes you don't have to decide for one over the other.

有时,您不必决定两者之间的关系。

In Go, for example, you can have both at the same time:

例如,在 Go 中,您可以同时拥有两者:

type Person struct {
    Name string `json:"name" yaml:"name"`
    Age int `json:"age" yaml:"age"`
}