CMake JSON array iteration
JSON can hold several data types including arrays. This example iterates over a JSON array in CMake.
Suppose file “json.cmake” contains:
cmake_minimum_required(VERSION 3.19)
set(jarr "{
\"c\":[3,4,5]
}")
string(JSON L LENGTH ${jarr} "c")
math(EXPR L "${L}-1")
string(JSON t TYPE ${jarr} "c")
message(STATUS "type: ${t}")
foreach(i RANGE ${L})
string(JSON v GET ${jarr} "c" ${i})
string(JSON t TYPE ${jarr} "c" ${i})
message(STATUS "c[${i}] = ${v} ${t}")
endforeach()
This results in:
$ cmake -P json.cmake
-- type: ARRAY
-- c[0] = 3 NUMBER
-- c[1] = 4 NUMBER
-- c[2] = 5 NUMBER