Quote CMake JSON arguments
The CMake
string(JSON)
subcommands should have the “json-string” input variable
quoted
to avoid CMake interpreting any semicolon in the JSON string as a list separator.
This avoids CMake string(JSON ...) failures when the JSON string contains semicolons.
string sub-command JSON failed parsing json string:
{
"key1" : 42,
"key2" : "I like to write
* Line 3, Column 12
Syntax error: value, object or array expected.
.
Example
Suppose a JSON string contains one or more values with semicolons in any value.
In that case, the JSON string should be quoted to avoid the CMake string(JSON ...) failure.
cmake_minimum_required(VERSION 3.19)
string(JSON jstr SET "{}" "key1" 42)
if(CMAKE_VERSION VERSION_GREATER_EQUAL 4.3)
string(JSON val STRING_ENCODE "I like to write; my blog is about tech.")
else()
set(val [=["I like to write; my blog is about tech."]=])
endif()
string(JSON jstr SET "${jstr}" "key2" "${val}")
# Fails with a syntax error
# string(JSON a GET ${jstr} "key1")
# works as expeccted
string(JSON v1 GET "${jstr}" "key1")
string(JSON v2 GET "${jstr}" "key2")
message(STATUS "key1: ${v1}. key2: ${v2}")Related: CMake JSON array iteration