Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMakeLists parse file

I would like to parse a file (XML, JSON or similar) in my CMakeLists and set some variables accordingly.

For example, say I have the following file:

<root>
 <Object>
  <name = "my_name"/>
  <url = "my_url"/>
 </Object> 
 <Object>
  <name = "another_name"/>
  <url = "another_url"/>
 </Object> 
</root>

and then in my CMakeLists I would like to set a variable with all the names and another variable with all the urls.

Is that possible? I haven't found much on this topic.

like image 755
Halbarad Avatar asked Mar 02 '26 19:03

Halbarad


1 Answers

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_name
MY_URLS: my_url;another_url
like image 127
Kevin Avatar answered Mar 05 '26 13:03

Kevin