Home > Software design >  Use JQ Select to format a JSON data
Use JQ Select to format a JSON data

Time:07-07

Use JQ Select to format a JSON data JSON Data

{
    "header": [
        "key1: value1",
        "key2: value2",
        "key3: value3"
    ]
}

Need to convert the header array into object:

{
    "header": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"
    }
}

I have tried using

{header: [.header[]]}

But this converts into an array

{
    "header": [
        "key1: value1",
        "key2: value2",
        "key3: value3"
    ]
}

CodePudding user response:

.header |= (map(split(": ") | { (.[0]): .[1] }) | add)

Will produce:

{
  "header": {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
  }
}

Try it online


  • Update the header key .header |=
  • map() over the array items
  • split() on : to get the key and value
  • Create an object with first index as key, second as value { (.[0]): .[1] }
  • add them together to create a single object
  • Related