Crystal string and heredoc with escaped characters for JSON

TLDR: Clarify a problem why some JSON content could be not parsable via directives and how to fix it

Michael Nikitochkin
The Incident Commander
2 min readJul 7, 2022

--

Review the command: JSON.parse(%|{“foo”: “string with new line\n”}|) . It produces prase error:

The error printed hidden character as new line. It gave a hint, that something is not escaped. It looks like, JSON does allow to close a string on next lines:

How to fix the problem

A heredoc and string generally allows interpolation and escapes.

Interpolation can be disabled by using a non-interpolating string literal like %q() or escaping backslash \\ .

The opening heredoc identifier is enclosed in single quotes.

References

--

--

Michael Nikitochkin
The Incident Commander

software engineer. like ruby, crystal and golang. play with containers and kubernetes via terraform.