[SOLVED] Is there a built in arg to json.Marshal a []byte to UTF-8 instead of base64?

Issue

This Content is from Stack Overflow. Question asked by kidfrom

My goal is to send a struct in JSON format.

The problem is, the struct’s fields are mostly [][]byte.

The current solution that I can think of:

  1. Reiterate the fields and do string(field1).
  2. do atob(field1) in the front end.

I think the second solution is the better approach. Anyway, if there is a built in arg to json.Marshal a struct to UTF-8 instead of base64, it would be great.

Reproducible code main.go

package main

type response1 struct {
    Page   int
    Fruits []string
    Names  [][]byte
}

func main() {
    res1D := &response1{
        Page:   1,
        Fruits: []string{"apple", "peach", "pear"},
        Names:  [][]byte{[]byte("jack"), []byte("james")}}
    res1B, _ := json.Marshal(res1D)
    fmt.Println("res1B", string(res1B))
}



Solution

No, but you can write a custom MarshalJSON, which will be used in a json.Marshal instead of the default action

type response1 struct {
    Page   int
    Fruits []string
    Names  [][]byte
}

func (r response1) MarshalJSON() ([]byte, error) {
    var names []string
    for _, n := range r.Names {
        names = append(names, string(n))
    }
    return json.Marshal(struct {
        Page   int
        Fruits []string
        Names  []string
    }{
        Page:   r.Page,
        Fruits: r.Fruits,
        Names:  names,
    })
}


This Question was asked in StackOverflow by kidfrom and Answered by slsy It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?