Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method

Psych.safe_load

safe_load(yaml, permitted_classes: [], permitted_symbols: [], aliases: false, filename: nil, fallback: nil, symbolize_names: false, freeze: false, strict_integer: false)

Safely load the yaml string in yaml. By default, only the following classes are allowed to be deserialized:

Recursive data structures are not allowed by default. Arbitrary classes can be allowed by adding those classes to the permitted_classes keyword argument. They are additive. For example, to allow Date deserialization:

Example
Psych.safe_load(yaml, permitted_classes: [Date])

Now the Date class can be loaded in addition to the classes listed above.

Aliases can be explicitly allowed by changing the aliases keyword argument. For example:

Example
x = []
x << x
yaml = Psych.dump x
Psych.safe_load yaml               # => raises an exception
Psych.safe_load yaml, aliases: true # => loads the aliases

A Psych::DisallowedClass exception will be raised if the yaml contains a class that isn’t in the permitted_classes list.

A Psych::AliasesNotEnabled exception will be raised if the yaml contains aliases but the aliases keyword argument is set to false.

filename will be used in the exception message if any exception is raised while parsing.

When the optional symbolize_names keyword argument is set to a true value, returns symbols for keys in Hash objects (default: strings).

Example
Psych.safe_load("---\n foo: bar")                         # => {"foo"=>"bar"}
Psych.safe_load("---\n foo: bar", symbolize_names: true)  # => {:foo=>"bar"}
See also .safe_dump .safe_load_file .parse_stream .to_json also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0