CMakeLists parse file
As of CMake 3.19, you can use CMake to query and modify JSON strings using the string(JSON ...)
command.
If you have a JSON file like this:
[ { "name": "my_name", "url": "my_url" }, { "name": "another_name", "url": "another_url" }]
you can read the file, and create CMake variables containing the names and URLs from the JSON file.
# Read the JSON file.file(READ ${CMAKE_CURRENT_SOURCE_DIR}/myjson.json MY_JSON_STRING)# Loop through each element of the JSON array (indices 0 though 1).foreach(IDX RANGE 1) # Get the name from the current JSON element. string(JSON CUR_NAME GET ${MY_JSON_STRING} ${IDX} name) list(APPEND MY_NAMES ${CUR_NAME}) # Get the URL from the current JSON element. string(JSON CUR_URL GET ${MY_JSON_STRING} ${IDX} url) list(APPEND MY_URLS ${CUR_URL})endforeach()message("MY_NAMES: ${MY_NAMES}")message("MY_URLS: ${MY_URLS}")
This CMake code prints:
MY_NAMES: my_name;another_nameMY_URLS: my_url;another_url
CMake does not provide an json or XML parser by itself. However you can use tool like jq or xmlstarlet.You can call the tools with execute_process or add_custom_command from CMake depending on your needs.
jq: https://stedolan.github.io/jq/
xmlstarlet: http://xmlstar.sourceforge.net/overview.php