Suppose I have a JSON file like this:
{
"a": 1,
"b": [1, 2],
"c": [{
"x": 1
}, {
"x": 2
}]
}
This is my JSON model.
Then I have a text file like this:
A is {.a} and B is an array {.b}.
There is also c[].x = {.c[].x}
This is my template. Curly braces can be replaced with anything else, if it makes the rendering easier.
When that template is rendered against the aforementioned JSON model we should get this:
A is 1 and B is an array [1,2].
There is also c[].x = [1,2]
Does jq allow us to perform such a rendering?
Right now I use envsubst
to do this kind of things (the template looks differently, of course), but it is too messy.
2
Answers
Let’s assume
input.json
contains your json input, and template.txt contains(Notice I changed slightly the third jq expression to make it an array.)
Following perl script produeces expected ouput.
Output:
You may need to adapt above script if your template becomes more complex.
Also be aware that above script extracts jq script from template, so you need to have total control of the template to avoid code injection issue.
Here’s a jq-only solution to the stated problem.
With your text input and $json set to the given JSON:
produces:
For a bit more generality, you’d want to add more
gsub
filters.