Converting JSON object to Array using JQ

Viewed 396

I am trying to convert map of objects to an array with jq

My Input is

{
  "fish-chips": {
    "likeDislikeRatio": ["80%", "20%"],
    "country": ["BRIT_FOOD","USA_FOOD"]
  },
  "sausage": {
    "likeDislikeRatio": ["75%", "25%"],
    "country": ["EU_FOOD"]
  },
  "cheese-burger": {
    "likeDislikeRatio": ["25%", "75%"],
    "country": [
      "BRIT_FOOD",
      "USA_FOOD",
      "EU_FOOD",
      "DEFAULT"
    ]
  }
}

And my expected output is

[
  {
"name" : "fish-chips",    
"likeDislikeRatio": [
      "80%",
      "20%"
    ],
    "country": [
      "BRIT_FOOD",
      "USA_FOOD"
    ]
  }
]
[
  {
"name" : "sausage",
    "likeDislikeRatio": [
      "75%",
      "25%"
    ],
    "country": [
      "EU_FOOD"
    ]
  }
]
[
  {
"name" : "cheese-burger",
    "likeDislikeRatio": [
      "25%",
      "75%"
    ],
    "country": [
      "BRIT_FOOD",
      "USA_FOOD",
      "EU_FOOD",
      "DEFAULT"
    ]
  }
]

what I tried The closest filter I could find was to_entries[] | [.key, .value]

but the output is not as what I expected and I feel that there should be one more filter with this to get the desired out put

Current Output

[
  "fish-chips",
  {
    "likeDislikeRatio": [
      "80%",
      "20%"
    ],
    "country": [
      "BRIT_FOOD",
      "USA_FOOD"
    ]
  }
]
[
  "sausage",
  {
    "likeDislikeRatio": [
      "75%",
      "25%"
    ],
    "country": [
      "EU_FOOD"
    ]
  }
]
[
  "cheese-burger",
  {
    "likeDislikeRatio": [
      "25%",
      "75%"
    ],
    "country": [
      "BRIT_FOOD",
      "USA_FOOD",
      "EU_FOOD",
      "DEFAULT"
    ]
  }
]

I saw many posts on doing the opposite that is converting array to map using either reduce or INDEX but not what I expected.

1 Answers

You were close.

to_entries[] | [{name: .key} + .value]

Online demo

Related