如何使用jq创建一个JSON对象

huangapple go评论68阅读模式
英文:

How to use jq to create a JSON object

问题

{
  "abc": {
    "name": "abc"
  },
  "xyz": {
    "name": "xyz"
  }
}
英文:

I have the following JSON object:

{
...,
"projects": [
    "abc",
    "xyz"
  ],
...
}

And I want it transformed to:

{
  "abc": {
    "name": "abc"
  },
  "xyz": {
    "name": "xyz"
  },
}

I'm having trouble creating this. I've tried using map as .projects | map({(.): { "name": (.) }} ) but it's not in the format I want and ends up in an array.

答案1

得分: 2

你在寻找这样的内容:

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

在线演示

英文:

You're looking for something like this:

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

<sup>Online demo</sup>

答案2

得分: 1

我有一种功能性思维,所以我会在这里使用 reduce 函数:

reduce .projects[] as $name ({}; . + {($name): {name: $name}})

输出结果:

{
  "abc": {
    "name": "abc"
  },
  "xyz": {
    "name": "xyz"
  }
}
英文:

I have a bit of a functional mindset, so I'd reach for reduce here:

reduce .projects[] as $name ({}; . + {($name): {name: $name}})

outputs

{
  &quot;abc&quot;: {
    &quot;name&quot;: &quot;abc&quot;
  },
  &quot;xyz&quot;: {
    &quot;name&quot;: &quot;xyz&quot;
  }
}

huangapple
  • 本文由 发表于 2023年6月15日 00:38:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76475789.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定