0

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.

peak
  • 105,803
  • 17
  • 152
  • 177
Foobar
  • 7,458
  • 16
  • 81
  • 161

2 Answers2

1

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)
peak
  • 105,803
  • 17
  • 152
  • 177
  • What does `|=` do? From my understanding `|` passes the value on the left into the value on the right. – Foobar Jan 02 '20 at 03:47
  • See "Update-assignment: |=" in the jq manual (https://stedolan.github.io/jq/manual/) – peak Jan 02 '20 at 04:08
0

The solution turned out to be

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

I'm guessing .test=.test|fromjson confused jq

Foobar
  • 7,458
  • 16
  • 81
  • 161