297
array_with_three_elements:
- 1
- 2
- 3

empty_array:

Is there any way to specify that empty_array: is an array with no elements, such as with []? When I load it into a ruby hash I'd like it to know that it's an array.

Thanks

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Julian Mann
  • 6,256
  • 5
  • 31
  • 43

1 Answers1

476

Try using [], like:

empty_array: []

So in Ruby you have:

x = YAML::load("empty_array: []")
x # => {"empty_array" => []}
maerics
  • 151,642
  • 46
  • 269
  • 291
  • 36
    I just wanted to add that you can go into irb and type something like: "require 'yaml'; YAML::dump({ :hi => [] })" to see what the yaml should be for an object. – Mike A. Feb 24 '11 at 21:15
  • 33
    I'd just like to point out that JSON is an official subset of YAML 1.2 and almost a subset of earlier versions. Thus `[]` works for an empty sequence, `""` works for an empty string, and `{}` works for an empty mapping. – Daniel H Sep 24 '12 at 01:49
  • 4
    @DanielH Note that YAML parsers may not support line breaks inside `[]` or `{}` structures, which is a major incompatibility with JSON (copy-paste from [Wikipedia](http://en.wikipedia.org/wiki/Yaml#cite_note-10)) Cheers – oHo Feb 12 '13 at 10:51
  • 4
    Many parsers are still on YAML 1.1; this is probably what Wikipedia is talking about. The entire point of the 1.2 release is to make JSON an official subset. – Daniel H Feb 13 '13 at 18:18
  • how about strictyaml? – Xaser Apr 03 '20 at 13:46
  • 2
    The reason I ended up on this page is that `empty_array:[]` resulted in a parser error. It apparently only happens in certain contexts. `YAML::load("empty_array:[]")` works, `YAML::load("{empty_array:[]}")` fails, and `YAML::load("{empty_array: []}")` also works. Beware of whitespace in yaml. – maurice Sep 15 '21 at 16:59