Home > Software engineering >  Marshalling multidimensional array in Go
Marshalling multidimensional array in Go

Time:10-11

Code below, but the short version is I have a multidimensional array (slice) of uint8 in a struct. I tried to create a method that I could dump any struct into and it would write to a file, but the inner arrays are...well I'm not sure to be honest. The following is a succinct version of a larger code base but gets the point across. I am relatively new to Go so maybe its something about type conversions I'm just unaware of.

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
)

type MyStruct struct {
    MyArray [][]uint8 `json:"arr"`
    Name    string    `json:"name"`
}

func CreateMyStruct(name string, size uint16, fill uint8) *MyStruct {
    var m [][]uint8
    var i, j uint16
    for i = 0; i < size; i   {
        sl := []uint8{}
        for j = 0; j < size; j   {
            sl = append(sl, fill)
        }
        m = append(m, sl)
    }

    return &MyStruct{
        MyArray: m,
        Name:    name,
    }
}

func main() {
    myStruct := CreateMyStruct("bobby", 4, 1)
    fmt.Printf("% v\n", myStruct)
    str, _ := json.Marshal(myStruct)
    fmt.Printf("% v\n", str)
    ioutil.WriteFile("my.json", str, 0644)
}

The output being:

$ go run test.go
&{MyArray:[[1 1 1 1] [1 1 1 1] [1 1 1 1] [1 1 1 1]] Name:bobby}
[123 34 97 114 114 34 58 91 34 65 81 69 66 65 81 61 61 34 44 34 65 81 69 66 65 81 61 61 34 44 34 65 81 69 66 65 81 61 61 34 44 34 65 81 69 66 65 81 61 61 34 93 44 34 110 97 109 101 34 58 34 98 111 98 98 121 34 125]
$ cat my.json
{"arr":["AQEBAQ==","AQEBAQ==","AQEBAQ==","AQEBAQ=="],"name":"bobby"}

Obviously, I'm expecting something like:

[[1,1,1,1]] // etc

CodePudding user response:

In Golang []byte is an alias for []uint8 and json.Marshall encodes []byte as base64-encoded strings (as you're seeing):

https://pkg.go.dev/encoding/json#Marshal

I suspect the solution is to write your own JSON Marshaller to generate JSON as you want.

An example of a custom Marshaller is included in the docs for the package:

https://pkg.go.dev/encoding/json#example-package-CustomMarshalJSON

Here: https://play.golang.org/p/N2K8QfmPNnc

Typed tediously on my phone, so apologies it's hacky

  • Related