2

I'm looking to use jq to automatically resolve any field which contains json as json, example:

Input

{
  "guaranteedPrizes": "[]",
}

Output

{
  "guaranteedPrizes": [],
}
peak
  • 105,803
  • 17
  • 152
  • 177
M. Christopher
  • 305
  • 3
  • 14
  • 2
    Can you post a more demonstrative input, if its just a single field in an object? or more than one field? – Inian Feb 08 '21 at 12:42
  • @Inian that's exactly this, but I'd like this to happen automatically without me mentioning the field's name, realising this is asking a lot – M. Christopher Feb 08 '21 at 12:47
  • 1
    You need to create a minimal, reproducible example and an output expected. When you mean automatically, do you mean all the fields? are your fields nested? – Inian Feb 08 '21 at 12:48
  • @Inian Huh, `fromjson` [doesn't work](https://jqplay.org/s/_9R0uj6oP6) in `map_values` for some reason (the original script was `map_values(. as $in | try fromjson catch $in)`, it doesn't work either). – oguz ismail Feb 08 '21 at 12:55
  • Possibly due to this - https://github.com/stedolan/jq/issues/2140 ? – Inian Feb 08 '21 at 12:58
  • Yeah, I guess.. – oguz ismail Feb 08 '21 at 13:01
  • @oguzismail https://jqplay.org/s/_9R0uj6oP6 this works, but how could we include the rest of the file back? we're missing the non json stuff? – M. Christopher Feb 08 '21 at 13:11

2 Answers2

2

For a generic solution, you might wish to consider walk/1, and for efficiency, avoid calling fromjson redundantly:

walk(if type == "string"
     then . as $x | try fromjson catch $x
     else . end)
peak
  • 105,803
  • 17
  • 152
  • 177
1

If you want to go off the “deep end” and try evaluating fromjson recursively:

def deep:
  walk(if type == "string"          
           then . as $x 
           | try (fromjson | deep)
             catch $x     
           else . end);
deep
peak
  • 105,803
  • 17
  • 152
  • 177