Aladine
Aladine

Reputation: 205

jsonnet - Removing all items from an array so they can be used without brackets

I have this long script that requires a specific format, but I am having problems with getting some conditions work.

I have tried this multiple ways but I always get an array, in other scenarios I have called each index... While that works its slow and does not scale.

Is there a simple way to just remove the array/brackets?

(Yes I don't work in jsonnet a lot)

Sample code:

local test123 = [
   {  
      foo_1: "bar_1",
      foo_2: "bar_1",
   },
   {  
      foo_1: "bar_10",
      foo_2: "bar_20",
   },
   {  
      foo_1: "bar_100",
      foo_2: "bar_30",
   },
];

local test = 3;

if test >= 1 then test123 else []

Output:

[
   {  
      foo_1: "bar_1",
      foo_2: "bar_1",
   },
   {  
      foo_1: "bar_10",
      foo_2: "bar_20",
   },
   {  
      foo_1: "bar_100",
      foo_2: "bar_30",
   },
]

Desired Output:

   {  
      foo_1: "bar_1",
      foo_2: "bar_1",
   },
   {  
      foo_1: "bar_10",
      foo_2: "bar_20",
   },
   {  
      foo_1: "bar_100",
      foo_2: "bar_30",
   },

Upvotes: 0

Views: 357

Answers (1)

jjo
jjo

Reputation: 3020

jsonnet will only emit valid JSON, while your desired output is not.

I.e. you'd need to post-process it with some other tools, couple examples below:

# NB: last comma is missing (as per original JSON manifest)
$ jsonnet foo.jsonnet | sed -E '/^\S/d'
   {
      "foo_1": "bar_1",
      "foo_2": "bar_1"
   },
   {
      "foo_1": "bar_10",
      "foo_2": "bar_20"
   },
   {
      "foo_1": "bar_100",
      "foo_2": "bar_30"
   }

# NB: more powerful handling via `jq`, tho no commas in output
$ jsonnet foo.jsonnet | jq '.[]'    
{
  "foo_1": "bar_1",
  "foo_2": "bar_1"
}
{
  "foo_1": "bar_10",
  "foo_2": "bar_20"
}
{
  "foo_1": "bar_100",
  "foo_2": "bar_30"
}

Upvotes: 1

Related Questions