Export code results to JSON file

Hello,
I want to make a JSON file with results of my code (represented as follows through a simple function testFunct). I tried to make a struct list but I’m not sure if this is the correct apporach. Can someone help? Thank you…

package main

import (
	"fmt"
)

func main() {
	type allResults struct {
	length, result int
	}
	
		
	out := []allResults {} 
	
	for i := 0; i < 10; i++ {
		n := allResults{length: i, result: testFunct(i)}
		out = append(out,n)
	}
	
	fmt.Println(out)
	
}
func testFunct(length int) int{
	return length*10
}

It is not clear for me what is your concern, but if you want to generate the slice of struct in your code just do this

  1. Add encoding/json in your import

  2. You need to export the fields of yur structure so make them uppercase

     type allResults struct {
     	    Length, Result int
         }
    
  3. Change all references tou your field from lowecase to uppercase

  4. To generate json string just do

     b, err := json.Marshal(out)
         if err != nil {
     	   panic(err)
        }
         fmt.Println(string(b))
    

HTH,
Yamil

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.