-1

How could I use JQ to parse the following JSON object and produce the output below?

JSON Input:

{
    "key1": {
        "a": "A"
    },
    "key2": {
        "b": "123"
    },
    "key3": {
        "c": ["C1", "C2"]
    }
}

Desired Output:

[
  "a": "A",
  "b": 123,
  "c": "C1",
  "c": "C2"
]
lbj-ub
  • 1,425
  • 2
  • 19
  • 34
  • 1
    Both your input and o/p is not valid. Check it out at json lint https://jsonlint.com/ – Inian Sep 01 '21 at 17:51
  • Sorry, updated the input. Does the output necessarily need to be in JSON format? I'd like to generate an array if possible through JQ and then iterate through it in my bash script. – lbj-ub Sep 01 '21 at 17:57
  • jq cannot produce such an expected output. You need an array of objects – Inian Sep 01 '21 at 18:02
  • Although @Inian's claim that jq cannot produce the output you say you want is not literally true, it is doubtful that the format you are asking for is going to be very useful. Since you mention you want output suitable for use in a bash script, why not tell us more about what the actual problem? – peak Sep 01 '21 at 19:18

1 Answers1

1

The following program produces the output shown below it:

def q: "\"\(.)\"";

.[]
| to_entries[]
| (.key|q) as $k
| if .value|type == "array"
  then .value[] | "\($k): \(q)"
  else "\($k): \(.value|q)"
  end

Output:

"a": "A"
"b": "123"
"c": "C1"
"c": "C2"

This, or something very much like it, should be sufficient for using in a bash script, but if you really want the format shown in the Q, feel free to fiddle around. A more useful way to spend your time would probably be to read up on jq-bash interoperability, e.g. here on SO:

... and many others.

peak
  • 105,803
  • 17
  • 152
  • 177