Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: convert lower level JSON to escaped string

Tags:

bash

jq

I am struggling to use jq to massage the input data so that the first level keys are preserved, while the lower level JSON gets converted to escaped strings.

Input JSON:

{
  "a": "1",
  "b": {
    "c": "2",
    "d": {
      "e": "3"
    }
  },
  "f": "4"
}

Desired output:

{
  "a": "1",
  "b": "{ \"c\": \"2\", \"d\": { \"e\": \"3\"} }",
  "f": "4"
}

Is there a "pure" jq solution to this?

like image 276
horia Avatar asked Dec 06 '25 14:12

horia


1 Answers

with_entries and tostring seem to do the trick:

$ jq 'with_entries(.value |= tostring )' example.json                                               
{
  "a": "1",
  "b": "{\"c\":\"2\",\"d\":{\"e\":\"3\"}}",
  "f": "4"
}
like image 108
Shawn Avatar answered Dec 09 '25 04:12

Shawn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!