Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...