Search code examples
jqfromjson

jq, re-assign field if it is a string with its parsed JSON representation


I have the following JSON:

[
{
    "test": "[\"example\"]"
},
{

    "test": ["example2"]
}
]

For each object, I want to 1] check if "test" is a string and 2] if test is a string, parse it into an actual JSON array and then re-assign it. So the output would be:

[
{
    "test": ["example"]
},
{

    "test": ["example2"]
}
]

I have tried the following code: map(if .test|type == "string" then .test= .test|fromjson else . end). However, I get an error saying only strings can be parsed. I assume this is because jq thinks .test is not a string, but, I know .test is a string because of the if statement, so I'm not sure what is wrong.


Solution

  • The jq filter can be simplified to:

    map(if .test|type == "string" then .test |= fromjson else . end)
    

    or even:

    map(.test |= if type == "string" then fromjson else . end)