Search code examples
jsonjq

How do I replace a JSON string with its parsed equivalent in place with jq?


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 bs with their parsed form.

[
  {
    "a": 1,
    "b": { "c": 2 }
  },
]

How can I do this, ideally with jq?


Solution

  • Use fromjson, and update the fields in question using .[].b |=.

    .[].b |= fromjson
    

    Demo

    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? // .)
    

    Demo

    Both output:

    [
      {
        "a": 1,
        "b": {
          "c": 2
        }
      }
    ]