I have a JSON array with a bunch of objects, all the same keys, but some of the keys contain serialized JSON instead of actual JSON. Something like this.
[
{
"a": 1,
"b": "{\"c\":2}"
},
]
and I'd like to replace the contents of all the b
s with their parsed form.
[
{
"a": 1,
"b": { "c": 2 }
},
]
How can I do this, ideally with jq?
Use fromjson
, and update the fields in question using .[].b |=
.
.[].b |= fromjson
If you want to decode all JSON-encoded strings, unknowing which ones are, you could try
using fromjson
, and in case of a failure resort to the original input .
. try
can be abbreviated to ?
:
.[][] |= (fromjson? // .)
Both output:
[
{
"a": 1,
"b": {
"c": 2
}
}
]