Using jq, convert array of name/value pairs to obj

2020-04-18 05:46发布

问题:

Given a json file in the format as :

[
  {
    "name" : "A",
    "value" : "4"
  },
  {
    "name" : "B",
    "value" : "2"
  },
  {
    "name" : "C",
    "value" : {
      "X": "Something",
      "Y": "Else"
    }
  }
]

How would I convert it to something like this using jq:

{
  "A": "4",
  "B": "2",
  "C": {
    "X": "Something",
    "Y": "Else"
  }
}

I did come close using jq 'map( { (.name): .value } ) but that still leaves each object in its separate braces instead of having them all together.

回答1:

Using your approach, simply add add to your filter:

map( { (.name): .value } ) | add