Xianlin Xianlin - 2 months ago 17
JSON Question

jq json parser concate nested array object value

Hi I have the below JSON file with nested object:

{
"Maps": {
"Campus": [
{
"name": "nus",
"Building": [
{
"name": "sde1",
"Floor": [
{
"name": "floor1"
},
{
"name": "floor2"
}
]
},
{
"name": "sde2"
}
]
},
{
"name": "ntu",
"Building": [
{
"name": "ece1",
"Floor": [
{
"name": "floor1"
},
{
"name": "floor2"
}
]
},
{
"name": "ece2"
}
]
}
]
}
}


I want to use
jq
to parse the above JSON file and get the below format:

nus>sde1>floor1
nus>sde1>floor2
ntu>ece1>floor1
ntu>ece1>floor2


basically I have to concatenate the
Campus Name
with
Building Name
and
Floor name
and put a
<
symbol in between.

If the nested object field
Floor
is not exist, ignore the parse and continue the next child object.

How to achieve that? thanks.

Answer Source

You can use the following jq command:

jq '.Maps.Campus[]|"\(.name)>\(.Building[]|"\(.name)>\(.Floor[]?.name)")"' file.json

jq is smart enough to print the combinations of .name and .Building[].name since .Building is an array. The same action get's applied to .Building[].name and Floor[]?.name. ? because floor is not always set.