I have an existing string in CMake – compile flags passed to the target – that have quotes in them. If I want to write these to a JSON file, I need to escape the quotes in them. Since these are not defined manually by me in CMake, I can’t manually escape them. I could do a string replace of " with ", but I want to avoid massaging any parsing with regex/string replace in favor of a proper escaping API. Is there a way I can properly escape these strings so that they can be written to a JSON file?
Are you aware of the JSON functionality introduced in CMake 3.19?
https://cmake.org/cmake/help/latest/command/string.html#json
This appears to be related to issue 22252. I believe CMake does not provide a straightforward way to properly escape string variables for use with JSON.
You might find the json_esc
function from this gist useful as a workaround for CMake 3.19 and above. Please let me know if you find a bug.
There is string(CONFIGURE "${input}" output @ONLY ESCAPE_QUOTES)
that could be (ab)used (if @var@
doesn’t appear in the flags).
Note that \u
and other escapes won’t be handled though, so Windows paths may need some special care.