I have a problem where I’m receiving JSON that depending on the source, may have some data at root level or under another element.
From this JSON I need to extract multiple elements into a nother, normalized JSON, with custom keys for the values.
Sample JSON 1:
{"name":"John","last":"Smith","position": "clerk"}
Sample JSON 2:
{"personData": {"name":"John","last":"Smith"}}
I was using this at the beginning as all my test jsons had the first form:
jq '{nombre: .name, apellido: .last, puesto: .position}'
When they started coming up empty I tries using the // operator but it doesn’t seem to work if I’m providing the keys:
Doesn’t work:
jq '{nombre: .name//.personData.name, apellido: .last, puesto: .position}'
Works (but I don’t get any keys):
jq '{nombre: .name//.personData.name, apellido: .last, puesto: .position//null}'
I’ve never had to use jq with conditionals or logic like this, so I may be missing something obvious.
(actual json files are pretty extensive and whichever logic I need to use will end up applied to a dozen or so fields, so I’m looking for a sustainable solution.
Expected output would be for the first sample:
{"nombre" : "John", "apellido": "Smith", "puesto": "clerk" }
And for the second sample:
{"nombre" : "John", "apellido": "Smith", "puesto": null}
2
Answers
One of many possibilities:
One way: