Suppose that there is a JSON file (called array.json
) with the following structure:
{
"array":
[
{
"name" : "element1",
"property" : "value1"
},
{
"name" : "element2",
"property" : "value2"
}
]
}
I wonder how to use string(JSON) command to:
- INSERT a new element (
element3
) into the array betweenelement1
andelement2
? - PREPEND a new element (
element3
) into the array?
BTW, I already know how to APPEND a new element (element3
) into the array. The followings are my example codes:
Click to expand "json.cmake"
file(READ "${CMAKE_CURRENT_LIST_DIR}/array.json" jsonCnt)
message("---------- array.json (before) ----------")
message("${jsonCnt}")
string(JSON arrayCnt GET "${jsonCnt}" "array")
message("---------- array (before) ----------")
message("${arrayCnt}")
# Create the 3rd element
set(newElemCnt "{}")
string(JSON newElemCnt SET "${newElemCnt}" "name" "\"element3\"")
string(JSON newElemCnt SET "${newElemCnt}" "property" "\"value3\"")
# Append the 3rd element into the "array"
string(JSON arrayLen LENGTH "${arrayCnt}")
string(JSON arrayCnt SET "${arrayCnt}" ${arrayLen} "${newElemCnt}")
message("---------- array (after) ----------")
message("${arrayCnt}")
string(JSON jsonCnt SET "${jsonCnt}" "array" "${arrayCnt}")
message("---------- array.json (after) ----------")
message("${jsonCnt}")
Click to expand "array.json"
{
"array":
[
{
"name" : "element1",
"property" : "value1"
},
{
"name" : "element2",
"property" : "value2"
}
]
}
After running the command cmake -P json.cmake
in CLI, the output is:
Click to expand
---------- array.json (before) ----------
{
"array":
[
{
"name" : "element1",
"property" : "value1"
},
{
"name" : "element2",
"property" : "value2"
}
]
}
---------- array (before) ----------
[
{
"name" : "element1",
"property" : "value1"
},
{
"name" : "element2",
"property" : "value2"
}
]
---------- array (after) ----------
[
{
"name" : "element1",
"property" : "value1"
},
{
"name" : "element2",
"property" : "value2"
},
{
"name" : "element3",
"property" : "value3"
}
]
---------- array.json (after) ----------
{
"array" :
[
{
"name" : "element1",
"property" : "value1"
},
{
"name" : "element2",
"property" : "value2"
},
{
"name" : "element3",
"property" : "value3"
}
]
}
However, I just cannot figure out how to INSERT/PREPEND an element into the array. Is it possible to use the currently available subcommands (SET, GET, LENGTH, MEMBER…etc) of string(JSON) to implement these two operations?
If not, I would like to request the support for APPEND/INSERT/PREPEND subcommands of string(JSON).