Using jq, convert array of objects to object with named keys

不问归期 提交于 2019-12-18 18:55:12

问题


Given a json file in the format as :

[
 {
  name : "A",
  value : "1"
 },
 {
  name : "B",
  value : "5"
 },
 {
  name : "E",
  value : "8"
 }
]

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

{
 "A" : {
   name : "A",
   value : "1"
 },
 "B" : {
  name : "B",
  value : "5"
 },
 "E" : {
  name : "E",
  value : "8"
 }
}

jq '{(.[].name) : "the name"}' 'myfile.json' gets me an object with [].name keys but how do I assign the object to it?


回答1:


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

(The tostring is for safety/robustness.)

INDEX/1

If your jq has INDEX/1 (introduced after the release of version 1.5), you can simply write:

INDEX(.name)



回答2:


Just build up a new object going through the items in the array. Add the items to the object with the name as the key.

reduce .[] as $i ({}; .[$i.name] = $i)


来源:https://stackoverflow.com/questions/42427725/using-jq-convert-array-of-objects-to-object-with-named-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!