jsonnet

jsonnet - output multiple files from seed array


Just getting started with jsonnet. My goal is to generate multiple json files from template json and seed array.

I've seen that you can use for syntax to iterate and also the the Multiple File Output section under the Getting Started but not how to make this work from a single json template https://jsonnet.org/learning/getting_started.html

Imagine the json template has id and colours as variable and perhaps other fields are static like enabled

{ 
  id: x.id, 
  colours: x.colours, 
  enabled: true 
}

and maybe the seed values - i'm not committed to this format, the following is more to give you example of data to be fed to the template to produce 2 files

{
  'basic.json': { id: 'basic', colours: ['white',black'] },
  'standard.json': { id: 'standard', colours: ['red','green'] },
}

goal output

$ jsonnet -m . multiple_output.jsonnet
basic.json
standard.json

$ cat basic.json 
{ 
  id: 'basic', 
  colours: ['white',black'], 
  enabled: true 
}

$ cat standard.json 
{ 
  id: 'standard', 
  colours: ['red','green'], 
  enabled: true 
}

Any direction of where to go with this would be great - Thanks.


Solution

  • If I understood you correctly, below code should achieve what you need:

    NOTE btw that your basic.json and standard.json expected output examples are not valid JSON, in particular the keys are not quoted.

    foo.json

    [
      { "id": "basic", "colours": ["white","black"] },
      { "id": "standard", "colours": ["red","green"] }
    ]
    

    foo.jsonnet

    local input = import 'foo.json';
    
    local template = {
      id: error 'id is required',
      colours: [],
      enabled: true,
    };
    
    // Small wrapper function to make final comprehension more readable
    local fileName(entry) = '%s.json' % entry.id;
    
    // Create object keyed by `fileName(entry)`, with value
    // as result of merging template and entry from input array
    { [fileName(entry)]: template + entry for entry in input }
    

    output

    $ jsonnet -m . foo.jsonnet
    ./basic.json
    ./standard.json
    $ cat basic.json
    {
       "colours": [
          "white",
          "black"
       ],
       "enabled": true,
       "id": "basic"
    }
    $ cat standard.json
    {
       "colours": [
          "red",
          "green"
       ],
       "enabled": true,
       "id": "standard"
    }