kajacx
kajacx

Reputation: 12939

Stringify an object in YAML

Is there a way to stringify an object in YAML? I'm looking for something like this:

YAML input:

environment: @stringify(
   foo: buz,
   bar: 42,
)

Expected JSON output:

{"environment": "{\"foo\": \"buz\", \"bar\": 42}"}

I could of course do this:

environment: '{
    "foo": "buz",
    "bar": 42
}'

but that has several problems:

  1. No syntax check. YAML will happily compile, any syntax error inside the JSON will occur "downstream".
  2. No YAML support. I can't use insertion of objects inside (e.g. <<: *myObj).
  3. Extra whitespace. Newlines in the text can cause problems, especially if the file is written with CLRF endings.
  4. Strict JSON only. "Extra" JSON features like trailing commas or comments will not be removed, which is extra work "downstream".

Note: I'm using this for docker-compose, so if you have a solution specific for docker-compose, that would be fine too.

Upvotes: 1

Views: 1685

Answers (1)

F1ko
F1ko

Reputation: 4244

Here you can see the entire new YAML v1.2.2 specification (released October 1st 2021). It does specify something called a JSON schema, however, this is not what you are looking for.

Once you use YAML's string behavior it is going to be treated as a "normal" string without any specific formation linting (other than the required escaping of characters and so on).

There is no native YAML or docker-compose way to do what you are intending to do. Since you specified that you are not looking for any scripts or 3rd party programs the answer is:

No, it is not possible.

Upvotes: 2

Related Questions