Reputation: 23
How to convert this ["a", "b", "c", "d"]
into
"a", "b", "c", "d"
in JSONNET (https://jsonnet.org/ref/stdlib.html)
Upvotes: 2
Views: 3035
Reputation: 2991
There exists an std.toString
function, which might do want you want. For example std.toString(["a", "b", "c", "d"])
results in a string ["a", "b", "c", "d"]
. It is slightly different from your example output "a", "b", "c", "d"
.
If you want to have exactly the format that you want, you can of course build the string yourself. The most obvious way is writing a recursive function (that's how you iterate in Jsonnet):
local arrayToString(arr) =
local aux(arr, index) =
// Assuming escapeStringJson is how you want to serialize
// the elements. Of course you can use any other way
// to serialize them (e.g. toString or manifestJson).
local elem = std.escapeStringJson(arr[index]);
if index == std.length(arr) - 1 then
elem
else
elem + ", " + aux(arr, index + 1)
;
aux(arr, 0);
arrayToString(["a", "b", "c", "d"])
A more idiomatic way would be to use map to transform all elements of the array and then join to merge them into one string:
local arrayToString(arr) = std.join(", ", std.map(std.escapeStringJson, arr));
arrayToString(["a", "b", "c", "d"])
Upvotes: 2