2

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

So I have to loop through and cast everything to int or something to make it work? Is there a better way?
No, your code is fine. I've added a link to the docs where a custom Marshaller is shown. You can write one that outputs a more literal JSON equivalent rather than base64 encode them
You're very welcome!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.