Home > database >  jq: Wrap all first-level atomic values with a list
jq: Wrap all first-level atomic values with a list

Time:08-18

Suppose we have a JSON:

{
 "a" : 23,
 "b" : "hi",
 "c": [90],
 "d": [{"j" : 80}]
}

I want to convert this to

{
 "a" : [23],
 "b" : ["hi"],
 "c": [90],
 "d": [{"j" : 80}]
}

How do I do this using jq?

CodePudding user response:

You could update |= each field .[] using an if statement based on the value's type:

.[] |= if type == "array" then . else [.] end
{
  "a": [
    23
  ],
  "b": [
    "hi"
  ],
  "c": [
    90
  ],
  "d": [
    {
      "j": 80
    }
  ]
}

Demo

Instead of checking the type against array, you could also just update scalars, which are all non-iterables, i.e. no arrays and no objects:

(.[] | scalars) |= [.]
{
  "a": [
    23
  ],
  "b": [
    "hi"
  ],
  "c": [
    90
  ],
  "d": [
    {
      "j": 80
    }
  ]
}

Demo

CodePudding user response:

Please try this:

jq 'with_entries(.value|=([.]|flatten))' input.json
  • Related