CanadianJeff CanadianJeff - 1 month ago 15
JSON Question

using jq to iterate json data

I have some json input data I would like to extract the variable values into something I can paste into my script

input sample:

{
"menu": {
"props": [{
"name": "foo1",
"model": "bar1"
}, {
"name": "foo2",
"model": "bar2"
}, {
"name": "foo3",
"model": "bar3"
}, {
"name": "foo4",
"model": "bar4"
}, {
"name": "foo5",
"model": "bar5"
}]
}
}


desired output:

AddMenuItem(menu, "bar1", "foo1");
AddMenuItem(menu, "bar2", "foo2");
AddMenuItem(menu, "bar3", "foo3");
...etc

Answer

Something like this would work:

$ jq -r '.menu.props[] | "AddMenuItem(menu, \"\(.model)\", \"\(.name)\")"' file.txt
AddMenuItem(menu, "bar1", "foo1")
AddMenuItem(menu, "bar2", "foo2")
AddMenuItem(menu, "bar3", "foo3")
AddMenuItem(menu, "bar4", "foo4")
AddMenuItem(menu, "bar5", "foo5")

-r prints raw output (Not JSON encoded).

Unwrapping the props array with [] and printing the string "AddMenu..." for each element in said array.

One can also use ...props | map("AddMenu...")[] which might be more intuitive.

\(...) enables string interpolation between ( and ).

Comments