Skip to content

Compatibility with Modern Flavors of JSON #7

Open

Description

@Kira-NT

Introduction

YAML 1.2 is, by design, a superset of JSON. Unfortunately, though, the neat feature of being able to process both JSON and YAML with the same conforming YAML parser has become increasingly irrelevant over the years due to the widespread adoption of extended JSON formats that support C-style comments (with one of the most prominent of them being JSONC), to the point where most major JSON parsers, while strict by default, do provide an option to at the very least ignore comments encountered in a document.

Since YAML currently does not define any grammar for C-style comments, projects that need to process user-facing YAML and JSON files once again have to depend on both a YAML parser and a JSON parser. It would therefore be great if this de facto divergence between the standards could be reconciled so that YAML could once again become a superset of modern JSON.

Proposal

If we focus specifically on C-style comments as defined by JSONC, I see three steps that would be needed to support them in YAML:

Step 1: allow comments after commas, quoted scalars, and flow-terminating tokens (} and ]). At the moment, YAML effectively defines comments as #, forbidding them from appearing immediately after the aforementioned tokens. Interestingly, as far as I understand, sequences such as ,#, '#, "#, }#, and ]# are already completely unambiguous: there is no reasonable interpretation of # here other than a comment indicator. In fact, conforming YAML parsers such as YamlDotNet have to implement additional checks to actively reject this syntax in order to pass yaml-test-suite#9JBA, yaml-test-suite#X4QW, yaml-test-suite#CVW2, and yaml-test-suite#SU5Z. So, in my opinion, although allowing # in more scenarios would make the spec slightly heavier on the eye, it would actually result in cleaner and simpler implementations. This is something I think YAML should pursue even if the rest of this proposal won't make it into the specification.

Step 2: extend the comment indicator syntax to also include // and /*. This should be relatively straightforward: // already behaves exactly like #; and while /* does introduces a new concept of block comments into YAML, since C-style block comments are (in)famously non-nestable, it keeps their grammar relatively simple - instead of consuming input until the end of the line, the parser simply consumes everything until the next occurrence of */.

Step 3: allow comments immediately after literals. This is the most problematic step. JSONC allows constructs such as {"foo":null/*bar*/}, and there is no way around supporting them if YAML is to become compatible with it. The most "elegant" solution, at least in my opinion, is to allow comments immediately after literals such as null, true, false, numbers, and their variants. This would make the grammar quite a bit more complex; however, a YAML parser already needs to be able to spot these constructs, so the machinery required to support this change should already be present in conforming implementations.

Result

If the proposed changes were implemented as-is, YAML would become a proper superset of JSONC, capable of parsing things as horrible as:

{
    /*
     * Top comment.
     */
    /*0*/ /*1*/"foo"/*2*/ /*3*/:/*4*/ /*5*/false/*6*/ /*7*/,// 8
    // Middle comment.
    /*9*/"bar"/*10*/:/*11*/true//12
    /*
     * Bottom comment.
     */
}

If this ever makes it into the mainline YAML specification, it would almost certainly have to be a part of something like YAML 2.0, as it is technically a major breaking change. However, I honestly don't think there's a single human being on Earth who would look at the example above and expect it to be parsed the way current conforming parsers do:

{
    "/* * Top comment. */ /*0*/ /*1*/\"foo\"/*2*/ /*3*/:/*4*/ /*5*/false/*6*/ /*7*/": null,
    "// 8 // Middle comment. /*9*/\"bar\"/*10*/:/*11*/true//12 /* * Bottom comment. */": null
}

Instead of:

{
    "foo": false,
    "bar": true
}

Additionally, since I'm already playing around with implementing this proposal in YamlDotNet, I can say that, funnily enough, it doesn't break a single test in yaml-test-suite, apart from the aforementioned yaml-test-suite#9JBA, yaml-test-suite#X4QW, yaml-test-suite#CVW2, and yaml-test-suite#SU5Z that explicitly forbid comments in places where they would otherwise be perfectly fine. So while this is technically a big change, in practice it appears to be far less disruptive than one might initially expect.

Oh, and I've also seen quite a few people requesting support for block comments in various repos within this organization, often proposing some crazy syntax like #!. So, as a bonus, this proposal would address those requests as well.

Other Formats

While this proposal addresses compatibility with JSONC and its stricter variants, there is at least one notable JSON-like format that remains problematic - that being JSON5.

The issue with it lies not so much with its support for comments, but rather with it allowing unquoted object keys. So for YAML to be compatible with JSON5, it would need to interpret {a:1} as {"a":1} instead of {"a:1":null}, as it currently does.

I'm really not sure whether this can be reconciled with the current YAML grammar at this point. Honestly, it's also unclear whether doing so would be anywhere near worthwhile, given that JSON5 is nowhere near as popular and widely adopted as JSONC. In other words, while I can see a path for YAML to adopt C-style comments and become compatible with JSONC with relatively little breakage, JSON5 compatibility would require significantly more work, would almost certainly break a considerable amount of existing YAML, and would offer a much smaller practical benefit, so it's probably not worth considering, unless you have any good ideas on how this could be implemented.

Remaining Questions

  • Even if JSON5 compatibility is to be considered a non-goal, should comments immediately after unquoted keys still be allowed, given that this is completely irrelevant when parsing JSONC? E.g.:

    {
        foo/*bar*/: null
    }

Any thoughts, critiques, and/or counter-proposals would be greatly appreciated, as I'd like to implement this feature in YamlDotNet in a way that has a realistic chance of eventually becoming a part of the YAML specification, or at the very least a widely supported extension to it :)

Activity

  1. ingydotnet commented on Jul 30, 2026

    @ingydotnet
    Member

    Greetings @Kira-NT and thank you for posting this.

    Also, thank you for posting this here. In my opinion that this is the perfect place to take on the conversation.
    That's because YAMLStar is committed to providing a plugin system that will allow deep changes to be made in YAML processing.
    Even those that don't conform to the spec.
    Plugins aren't enabled by default, so we have the chance to do interesting and optional things with YAML processing here, and have those things be available to all the YAMLStar languages (32 and counting...).

    Also, I maintain other important YAML implementations like pyyaml, libyaml and go-yaml. I'm already creating the plugin system in go-yaml but YAMLStar is really the best place to try out new ideas.

    Taking this on at the spec level from the get go is a fool's errand as no two YAML implementations are fully interoperable.
    Sad but true.
    Also YAML 1.2 has been out for 17 years and many of the most important implementations are still on YAML 1.1.
    Putting out a YAML 2.0 first and then waiting for the implementations to follow is a non-starter even in the AI age.

    YAMLStar works the same in every language, and allows us to try new things and see what works everywhere.
    Then when we have clear idea of what to put in a 2.0 spec we can put it out knowing that it is already supported in every language.

    BTW, I wonder if you had already come across yaml/www.yaml.org#196 where I encouraged the author to post about that here.

    I'll end this comment now and start addressing your ideas in another comment shortly.

  2. ingydotnet commented on Jul 30, 2026

    @ingydotnet
    Member

    I'll start by saying that I'm bullish on exploring this and I think a lot can be done to get closer to JSONC behavior.
    I'm assuming you don't want to do anything with the comment data itself and that roundtripping them is off the table.

    I think that your idea of modifying the productions for comments won't work. But...
    What you are really asking for is modifying what constitutes separating whitespace.

    Here are the relevant comment productions:

    [12] c-comment          ::= '#'
    [75] c-nb-comment-text  ::= c-comment nb-char*
    [76] b-comment          ::= b-non-content | <end-of-input>
    [77] s-b-comment        ::= ( s-separate-in-line c-nb-comment-text? )? b-comment
    [78] l-comment          ::= s-separate-in-line c-nb-comment-text? b-comment
    [79] s-l-comments       ::= ( s-b-comment | <start-of-line> ) l-comment*
    

    and here are the productions for separating whitespace:

    [31] s-space             ::= x20
    [32] s-tab               ::= x09
    [33] s-white             ::= s-space | s-tab
    [66] s-separate-in-line  ::= s-white+ | <start-of-line>
    [80] s-separate(n,c)     ::= s-separate-lines(n)    # BLOCK-OUT/IN, FLOW-OUT/IN
                                 s-separate-in-line     # BLOCK-KEY, FLOW-KEY
    [81] s-separate-lines(n) ::= ( s-l-comments s-flow-line-prefix(n) )
                               | s-separate-in-line
    

    if YAMLStar had a parser that could be configured to swap out productions by configuration then it would be simple to try this out and see where things landed with real world data.

    Very fortunately, YAMLStar currently does use a parser that has a function matching every spec production.
    See https://github.com/yaml/yaml-reference-parser-clj/blob/main/src/yaml_parser/grammar.cljc

    I think I should be able to craft a working prototype in the language(s) of your choice fairly soon.

    Let me know what you think.

  3. Kira-NT commented on Aug 7, 2026

    @Kira-NT
    Author

    Taking this on at the spec level from the get go is a fool's errand as no two YAML implementations are fully interoperable.

    I absolutely agree with that. Updating any kind of spec that's been stable for a while is an almost impossible task. And when it's something as widely used as YAML, it becomes even more difficult. So, implementing a feature as an optional extension first, checking whether it gets adopted by the industry, and only then formalizing what has become a de facto standard into the actual specification is indeed a really good idea, and, I believe, the way to go in this case.

    BTW, I wonder if you had already come across yaml/www.yaml.org#196 where I encouraged the author to post about that here.

    That is indeed where I came from! More than that, similarly to the OP, I also came from the YamlDotNet repo.

    One of my projects needs to be able to parse both JSONC and YAML, which means I need to bring in separate parsers for both of them, inflating the footprint of the final executable. So, I went to YamlDotNet to see if anyone had ever suggested adding optional support for C-style comments there, found the author of that thread complaining about the exact same thing, and, through a chain of linked issues, ended up here.

    What motivated me to open this issue is that implementing opt-in support for C-style comments in YamlDotNet ended up being surprisingly easy. More importantly, even with it enabled, the parser still passed all the meaningful tests in the yaml-test-suite. So, looking at that, I could actually see a world where, in a decade or two, this feature could become a part of a new standard. Hence, I felt it would be a missed opportunity not to, at the very least, start this conversation and share my thoughts and findings on the matter.

    I'll start by saying that I'm bullish on exploring this and I think a lot can be done to get closer to JSONC behavior.

    That's great to hear :)

    I'm assuming you don't want to do anything with the comment data itself and that roundtripping them is off the table.

    Well, yeah, comments are just that - comments. If a parser wants to provide a way to access their data, it's free to do so, but it shouldn't affect the parsed document otherwise.

    I think that your idea of modifying the productions for comments won't work. But... What you are really asking for is modifying what constitutes separating whitespace.

    Oh, yeah, sure. When I'm talking about ,#, '#, "#, }#, and ]#, I'm not literally suggesting turning these sequences into comment markers. I'm merely outlining the effect that should be achieved by whatever steps are necessary to accomplish it. I've never worked on creating a formal language specification, so my terminology is rather lacking in that regard.

    Let me know what you think.

    Everything sounds great!

  4. ingydotnet commented on Sep 8, 2026

    @ingydotnet
    Member

    @Kira-NT It took a while but YAMLStar now has a json-comments plugin.

    There are currently 2 ways to test it out and I'll show you both.

    Installing YAMLStar installs a binary CLI called yaml. The --plugin=json-comments enables JSON comments.

    $ cat a.yaml
    k1: v1//content
    k2: v2 //comment
    k3: https://not-a-comment.com
    k4: [foo, /*comment*/ bar]
    k5: 1.23// comment
    k6: false// comment
    $ source <(curl -sL yamlstar.org/install)
    Installed YAMLStar CLI - version 0.1.21
    Installed /home/ingy/.local/lib/libyamlstar-glojure.so - version 0.1.21
    $ yaml a.yaml 
    {"k1":"v1//content","k2":"v2 //comment","k3":"https://not-a-comment.com","k4":["foo","/*comment*/ bar"],"k5":"1.23// comment","k6":"false// comment"}
    $ yaml a.yaml -J
    {
      "k1": "v1//content",
      "k2": "v2 //comment",
      "k3": "https://not-a-comment.com",
      "k4": [
        "foo",
        "/*comment*/ bar"
      ],
      "k5": "1.23// comment",
      "k6": "false// comment"
    }
    $ yaml --plugin=json-comments a.yaml -J
    {
      "k1": "v1//content",
      "k2": "v2",
      "k3": "https://not-a-comment.com",
      "k4": [
        "foo",
        "bar"
      ],
      "k5": 1.23,
      "k6": false
    }
    $ 
    

    Note that the yaml CLI will install the plugin for you the first time you run it.

    I also add plugin support to the Python binding (other languages to follow).
    Python is good because it has "wheels" for auto installing binaries, and there are 2 binaries involved here (and 2 Python packages).

    $ python --version
    Python 3.14.3
    $ python -mvenv venv
    $ source venv/bin/activate
    (venv) $ pip install yamlstar yamlstar-plugin-json-comments
    Collecting yamlstar
      Using cached yamlstar-0.1.21-py3-none-manylinux_2_31_x86_64.whl.metadata (7.0 kB)
    Collecting yamlstar-plugin-json-comments
      Using cached yamlstar_plugin_json_comments-0.1.4-py3-none-manylinux_2_28_x86_64.whl.metadata (4.7 kB)
    Using cached yamlstar-0.1.21-py3-none-manylinux_2_31_x86_64.whl (25.5 MB)
    Using cached yamlstar_plugin_json_comments-0.1.4-py3-none-manylinux_2_28_x86_64.whl (8.4 MB)
    Installing collected packages: yamlstar-plugin-json-comments, yamlstar
    Successfully installed yamlstar-0.1.21 yamlstar-plugin-json-comments-0.1.4
    
    [notice] A new release of pip is available: 25.3 -> 26.2.1
    [notice] To update, run: pip install --upgrade pip
    (venv) $ cat yaml-json.py 
    #!/usr/bin/env python3
    
    import sys, json, yamlstar
    import yamlstar_plugin_json_comments as json_comments
    
    yaml_in = sys.stdin.read()
    options = yamlstar.Options().plugin(yamlstar.json_comments())
    data = yamlstar.YAMLStar(options, install_plugins=False).load(yaml_in)
    json_out = json.dumps(data)
    
    print(json_out)
    (venv) $ python yaml-json.py < a.yaml 
    {"k1": "v1//content", "k2": "v2", "k3": "https://not-a-comment.com", "k4": ["foo", "bar"], "k5": 1.23, "k6": false}
    (venv) $ python yaml-json.py < a.yaml | jq
    {
      "k1": "v1//content",
      "k2": "v2",
      "k3": "https://not-a-comment.com",
      "k4": [
        "foo",
        "bar"
      ],
      "k5": 1.23,
      "k6": false
    }
    

    Let me know if you are able to get this working or not. Assuming it works, can you please try out all the various combinations you'd expect to work? Maybe there's a test suite for this?

    I'm looking forward to hearing about your experience and thoughts on this.

  5. Kira-NT commented on Sep 17, 2026

    @Kira-NT
    Author

    Hey! Unfortunately, I've been unable to run your examples on my machine. Both yaml-glojure itself and its Python bindings throw the same exception when attempting to use the json-comments plugin:

    Exception: load YAMLStar plugin venv/lib/python3.14/site-packages/yamlstar_plugin_json_comments/lib/libyamlstar-plugin-json-comments.so: venv/lib/python3.14/site-packages/yamlstar_plugin_json_comments/lib/libyamlstar-plugin-json-comments.so: undefined symbol: yamlstar_plugin_v1_parse
    

    There's probably meant to be a shared library like libyamlstar-plugin.so, but you forgot to actually pack it with the release :D

  6. ingydotnet commented on Sep 17, 2026

    @ingydotnet
    Member

    Hey! Unfortunately, I've been unable to run your examples on my machine. Both yaml-glojure itself and its Python bindings throw the same exception when attempting to use the json-comments plugin:

    There's probably meant to be a shared library like libyamlstar-plugin.so, but you forgot to actually pack it with the release :D

    You need the yamlstar-plugin-json-comments Python plugin which has wheels to install that shared lib.

    Try:

    $ pip install yamlstar yamlstar-plugin-json-comments==0.1.5
    $ python -c 'import yamlstar; print(yamlstar.YAMLStar(yamlstar.Options().plugin(yamlstar.json_comments())).load("a: b // c"))'
    {'a': 'b'}
    

    Apparently there's a bug in the latest version yamlstar-plugin-json-comments==0.1.6.

  7. ingydotnet commented on Sep 17, 2026

    @ingydotnet
    Member

    @Kira-NT yamlstar-plugin-json-comments 0.1.7 is released now so this should just work:

    $ pip install yamlstar yamlstar-plugin-json-comments
    $ python -c 'import yamlstar; print(yamlstar.YAMLStar(yamlstar.Options().plugin(yamlstar.json_comments())).load("a: b // c"))'
    {'a': 'b'}
    

    Also to use the YAMLStar cli (yaml) for this, you can run:

    $ source <(curl -sL in-1.cc) yamlstar
    √ yaml v0.1.21 installed to /home/ingy/.local/bin/yaml (0.21s)
    $ yaml --plugin=json-comments <<<'a: b // c'
    Installing YAMLStar plugin json-comments=json-comments 0.1.7
    Installed YAMLStar plugin at /home/ingy/.local/share/yamlstar/0.1.21/yamlstar-0.1.21/lib/libyamlstar-plugin-json-comments.so
    {"a":"b"}
    

    The CLI installs the plugin shared lib automatically there.

  8. ingydotnet commented on Sep 17, 2026

    @ingydotnet
    Member

    @Kira-NT I'm still "looking forward to hearing about your experience and thoughts on this."!!!

  9. Kira-NT commented on Sep 18, 2026

    @Kira-NT
    Author

    Thanks a lot for the quick update! yamlstar-plugin-json-comments 0.1.7 did indeed fix the issue!

    Answering one of your previous questions, I am not, unfortunately, aware of any conclusive test suite for JSONC parsers. Everybody seems to wing it more or less. I'd say the example I provided in the description of this issue is a pretty good stress test, though. And currently, yamlstar is unable to parse it :c

    All the obvious cases I could think of, like a comment after a comma, a bracket, or a literal, both with and without whitespace in between, seem to be working just fine. But I did identify at least one edge case that is, in fact, responsible for yamlstar not being able to parse my example - handling of multiple comments within the same key-value pair seems to be a bit off (which is probably rooted in the original assumptions made for pure YAML, where comments are exclusively single-line entities), so sometimes they get parsed incorrectly or not at all:

    printf '{"0":0}' | yaml --plugin=json-comments -         # {"0":0}
    printf '{"0":0/**/}' | yaml --plugin=json-comments -     # {"0":0}
    printf '{"0":/**/0/**/}' | yaml --plugin=json-comments - # {"0":"0/**/"}
    printf '{"0"/**/:0//\n}' | yaml --plugin=json-comments - # {"0":"0//"}
    printf '{/**/"0":0//\n}' | yaml --plugin=json-comments - # {"0":0}
    printf '{"0"//\n:0//\n}' | yaml --plugin=json-comments - # {"0":"0//"}
    printf '{/**/"0"/**/:0}' | yaml --plugin=json-comments - # Error: Parser finished before end of input
    printf '{/**/"0"//\n:0}' | yaml --plugin=json-comments - # Error: Parser finished before end of input

    Also, what set of rules did you end up settling on for your implementation? I know it's just a plugin, but it would be nice to have some of the ideas used here formalized, so that other people interested in providing experimental support for C-style comments in their own parsers could follow in the same footsteps and arrive at more or less consistent implementations :)

  10. ingydotnet commented on Sep 21, 2026

    @ingydotnet
    Member

    Thanks for digging in here!
    I'll have to see if I can fix these bugs.

    FYI, this command form can be simplified like so:

    printf '{/**/"0":0//\n}' | yaml --plugin=json-comments -
    <<<$'{/**/"0":0//\n}' yaml --plugin=json-comments
    

    I also found a bug:

    $ <<<$'{a: b /*xxxxx*/ c}' yaml --plugin=json-comments
    {"a":"b           c"}
    

    I see what I can do and also elaborate on the rules.

    However I would beware of adding this to other YAML loaders unless it is gated by an option or a plugin system.
    This is NOT valid YAML 1.2. Just an experiment.
    I'm not even sure I see the use case.

    I'm also adding a matching plugin system to yaml/go-yaml and have added the json-comments plugin there.
    The go-yaml project also has a CLI called go-yaml, and it can use the json-comments plugin just like YAMLStar.
    In fact the both use the same plugin code from https://github.com/yamlstar/yamlstar-plugin-json-comments

    Here's how to use the go-yaml CLI:

    git clone [email protected]:yaml/go-yaml
    cd go-yaml
    make cli CONFIG=<(echo '{plugin: {json-comments: true}}')
    ./go-yaml <<<'a: b // c' -j
    {"a":"b"}
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions