YAML和JSON之间有什么不同,特别是考虑到以下事情?

性能(编码/解码时间) 内存消耗 表达清晰 库可用性,易用性(我更喜欢C)

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

相关:

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


当前回答

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

其他回答

I find both YAML and JSON to be very effective. The only two things that really dictate when one is used over the other for me is one, what the language is used most popularly with. For example, if I'm using Java, Javascript, I'll use JSON. For Java, I'll use their own objects, which are pretty much JSON but lacking in some features, and convert it to JSON if I need to or make it in JSON in the first place. I do that because that's a common thing in Java and makes it easier for other Java developers to modify my code. The second thing is whether I'm using it for the program to remember attributes, or if the program is receiving instructions in the form of a config file, in this case I'll use YAML, because it's very easily human read, has nice looking syntax, and is very easy to modify, even if you have no idea how YAML works. Then, the program will read it and convert it to JSON, or whatever is preferred for that language. In the end, it honestly doesn't matter. Both JSON and YAML are easily read by any experienced programmer.

如果您关心更好的解析速度,那么可以选择将数据存储在JSON中。我必须从其他用户修改文件的位置解析数据,因此我使用YAML,因为与JSON相比,它提供了更好的可读性。 你还可以在YAML文件中添加注释,这在JSON文件中是做不到的。

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

在“YAML:与JSON的关系”一节中可以看到官方规范。

总的来说,我喜欢YAML的某些东西是JSON中没有的。

正如@jdupont指出的,YAML在视觉上更容易看。事实上,YAML主页本身就是有效的YAML,但是它很容易被人阅读。 YAML能够使用“锚”引用YAML文件中的其他项。因此,它可以像在MySQL数据库中一样处理关系信息。 YAML在YAML文件中嵌入其他序列化格式(如JSON或XML)方面更加健壮。

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

现在,AJAX和其他web技术倾向于使用JSON。YAML目前更多地用于脱机数据处理。例如,它默认包含在基于c语言的OpenCV计算机视觉包中,而JSON则没有。

您将发现JSON和YAML的C库。YAML的库往往更新,但我过去使用它们没有遇到过麻烦。参见Yaml-cpp的例子。

JSON编码六种数据类型:对象(映射)、数组、字符串数字、布尔值和Null。对于机器来说,它非常容易解析,并且提供很少的灵活性。说明书大约有一页半。

YAML allows the encoding of arbitrary Python data and other crazy crap (which leads to vulnerabilities when decoding it). It is hard to parse because it offers so much flexibility. The specification for YAML was 86 pages, the last time I checked. YAML syntax is obviously influenced by Python, but maybe they should have been a little more influenced by the Python philosophy on a few points: e.g. “there should be one—and preferably only one—obvious way to do it” and “simple is better than complex.”

与JSON相比,YAML的主要优点是更容易阅读和编辑,这使它成为配置文件的自然选择。

最近,我倾向于使用TOML作为配置文件。它不像YAML那样漂亮或灵活,但对机器和人类来说都更容易解析。该语法(几乎)是INI语法的超集,但它解析为类似json的数据结构,只添加了一种额外类型:日期类型。

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