programing tip

YAML과 JSON의 차이점은 무엇입니까?

itbloger 2020. 10. 2. 21:45
반응형

YAML과 JSON의 차이점은 무엇입니까?


특히 다음 사항을 고려할 때 YAML과 JSON의 차이점은 무엇입니까?

  • 성능 (인코딩 / 디코딩 시간)
  • 메모리 소비
  • 표현 선명도
  • 라이브러리 가용성, 사용 용이성 (C 선호)

구성 파일을 저장하기 위해 임베디드 시스템에서이 두 가지 중 하나를 사용할 계획이었습니다.

관련 :

Perl 데이터를 저장하려면 YAML 또는 JSON을 사용해야합니까?


기술적으로 YAML은 JSON의 상위 집합입니다. 이것은 이론적으로 적어도 YAML 파서가 JSON을 이해할 수 있지만 반드시 그 반대는 아님을 의미합니다.

"YAML : Relation to JSON" 섹션에서 공식 사양을 참조하십시오 .

일반적으로 JSON에서 사용할 수없는 YAML에 대해 내가 좋아하는 특정 사항이 있습니다.

  • 으로 @jdupont 지적 , YAML은 보는 시각 쉽습니다. 사실 YAML 홈페이지 는 그 자체로 유효한 YAML이지만 사람이 읽기 쉽습니다.
  • YAML에는 "앵커"를 사용하여 YAML 파일 내의 다른 항목을 참조하는 기능이 있습니다. 따라서 MySQL 데이터베이스에서 찾을 수있는 관계형 정보를 처리 할 수 ​​있습니다.
  • YAML은 YAML 파일 내에 JSON 또는 XML과 같은 다른 직렬화 형식을 포함하는 데 더 강력 합니다.

실제로이 마지막 두 가지 사항 중 어느 것도 사용자 또는 내가하는 일에 중요하지 않을 수 있지만 장기적으로 YAML이 더 강력하고 실행 가능한 데이터 직렬화 형식이 될 것이라고 생각합니다.

현재 AJAX 및 기타 웹 기술은 JSON을 사용하는 경향이 있습니다. YAML은 현재 오프라인 데이터 프로세스에 더 많이 사용되고 있습니다. 예를 들어 기본적으로 C 기반 OpenCV 컴퓨터 비전 패키지에 포함되어 있지만 JSON은 포함되어 있지 않습니다.

JSON 및 YAML 모두에 대한 C 라이브러리를 찾을 수 있습니다. YAML의 라이브러리는 새로운 경향이 있지만 과거에는 문제가 없었습니다. 예를 들어 Yaml-cpp를 참조하십시오 .


차이점 :

  1. YAML은 사용 방법에 따라 JSON보다 더 읽기 쉬울 수 있습니다.
  2. JSON은 종종 더 빠르며 더 많은 시스템과 여전히 상호 운용 가능합니다.
  3. "충분히 좋은"JSON 파서를 매우 빠르게 작성할 수 있습니다.
  4. 잠재적으로 유효한 JSON 중복 키 확실히 잘못된 YAML입니다.
  5. YAML에는 주석 및 관계형 앵커를 비롯한 수많은 기능이 있습니다. 따라서 YAML 구문은 매우 복잡하며 이해하기 어려울 수 있습니다.
  6. {a: &b [*b]}일부 변환기에서 무한 반복되는 yaml :에 재귀 구조를 작성할 수 있습니다 . 순환 탐지를 사용하더라도 "yaml bomb"은 여전히 ​​가능합니다 ( xml bomb 참조 ).
  7. 참조가 없기 때문에 JSON에서 개체 참조를 사용하여 복잡한 구조를 직렬화하는 것은 불가능합니다. 따라서 YAML 직렬화가 더 효율적일 수 있습니다.
  8. 일부 코딩 환경에서 YAML을 사용하면 공격자가 임의의 코드실행할 수 있습니다 .

관찰 :

  1. Python 프로그래머는 레벨을 표시하기 위해 대괄호 구문이 아닌 들여 쓰기를 사용하기 때문에 일반적으로 YAML의 열렬한 팬입니다.
  2. 많은 프로그래머들은 들여 쓰기에 "의미"를 붙이는 것이 좋지 않은 선택이라고 생각합니다.
  3. 데이터 형식이 애플리케이션의 환경을 벗어나거나 UI 내에서 구문 분석되거나 메시징 계층으로 전송되는 경우 JSON이 더 나은 선택 일 수 있습니다.
  4. YAML은 문법 정의와 같은 복잡한 작업에 직접 사용할 수 있으며 종종 새로운 언어를 개발하는 것보다 더 나은 선택입니다.

밀교 이론 우회

이것은 저처럼 구글 검색 결과에서 제목을 읽었 기 때문에 세부 사항이 아니라 제목에 대한 답이 되었기 때문에 웹 개발자 관점에서 설명 할 필요가 있다고 느꼈습니다 .

  1. YAML은 Python 개발자에게 익숙한 영역 인 공백 들여 쓰기를 사용합니다.
  2. JavaScript 개발자는 JSON이 JavaScript의 하위 집합이고 JavaScript 내에서 직접 해석 및 작성 될 수 있으며, JSON을 선언하는 약식 방법을 사용하여 공백없이 일반적인 변수 이름을 사용할 때 키에 큰 따옴표가 필요하지 않기 때문에 좋아합니다.
  3. YAML 및 JSON 모두에 대해 모든 언어에서 매우 잘 작동하는 수많은 파서가 있습니다.
  4. YAML의 공백 형식은보다 사람이 읽을 수있는 접근 방식이 필요하기 때문에 많은 경우에 훨씬 쉽게 볼 수 있습니다.
  5. YAML의 공백은 더 간결하고보기 쉬우면서도 편집기에 공백이나 들여 쓰기 줄 표시기가없는 경우 손으로 편집하기가 매우 어려울 수 있습니다.
  6. JSON은 검사 할 YAML보다 기능이 훨씬 적기 때문에 직렬화 및 역 직렬화가 훨씬 빠릅니다. 따라서 JSON을 처리하는 데 더 작고 가벼운 코드가 가능합니다.
  7. A common misconception is 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.

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.


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

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.

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

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.

Expressiveness

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

  • 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.

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.

Summary

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


GIT and YAML

The other answers are good. Read those first. But I'll add one other reason to use YAML sometimes: 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.

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.

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.)

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


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.

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?


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.


Technically YAML offers a lot more than JSON (YAML v1.2 is a superset of 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.
    
  • ...

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

Which one to choose?

  • YAML extra features and concise notation makes it a good choice for configuration files (non-user provided files).
  • JSON limited features, wide support, and faster parsing makes it a great choice for interoperability and user provided data.

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 license which 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).


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

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

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

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 cannot handle large data.

  • Not suitable for handling different multimedia formats.

  • JSON does not have a feature to support 'comments'. This could be included as an additional attribute alone.

  • YAML has some advantages over JSON like self-reference, support for complex datatypes, embedded block literals, comments and more.

  • JSON is only readable whereas YAML can be readable as well as editable.
  • JSON is a subset of YAML so that YAML parsers can be able to parse JSON.
  • YAML doesn't use any extra delimiters, so it is more light-weight than XML and JSON.

참고URL : https://stackoverflow.com/questions/1726802/what-is-the-difference-between-yaml-and-json

반응형