Export dashboard JSON

Your dashboard is defined in code, but Grafana needs JSON. The final step is to call build() on your builder to validate the configuration and produce the dashboard object, then serialize it to JSON and write it to a file.

To export your dashboard as JSON, complete the following steps:

Go

  1. Add the build and serialization logic to the end of your main() function in main.go:

    Go
      dashboardObj, err := builder.Build()
      if err != nil {
        log.Fatalf("failed to build dashboard: %v", err)
      }
    
      dashboardJson, err := json.MarshalIndent(dashboardObj, "", "  ")
      if err != nil {
        log.Fatalf("failed to marshal: %v", err)
      }
    
      err = os.WriteFile("dashboard.json", dashboardJson, 0644)
      if err != nil {
        log.Fatalf("failed to write file: %v", err)
      }
    
      log.Println("Dashboard written to dashboard.json")
  2. Run the program:

    Bash
    go run main.go

TypeScript

  1. Add the build and serialization logic to the end of your index.ts:

    typescript
    import * as fs from 'fs';
    
    const dashboardObj = builder.build();
    const json = JSON.stringify(dashboardObj, null, 2);
    fs.writeFileSync('dashboard.json', json, 'utf8');
    
    console.log('Dashboard written to dashboard.json');
  2. Run the program:

    Bash
    npx ts-node index.ts

What build() does

  1. Validates all configuration values. Invalid settings produce an error instead of broken JSON.
  2. Returns the final dashboard object with all panels, queries, and settings resolved
  3. Serializes to standard Grafana dashboard JSON, the same format the Grafana UI produces when you export a dashboard

You should now have a dashboard.json file in your project directory.

In the next milestone, you verify the output is valid and review its structure.


page 6 of 8