Skip to content

Instantly share code, notes, and snippets.

@locona
Created August 20, 2019 09:27
Show Gist options
  • Save locona/366c2499515a77848353c42cf1675f4b to your computer and use it in GitHub Desktop.
Save locona/366c2499515a77848353c42cf1675f4b to your computer and use it in GitHub Desktop.
How to change to json string without escaping.
package main
import (
"encoding/json"
"fmt"
)
type IDType struct {
Value int
Valid bool
}
type Parent struct {
ID interface{} `json:"id"`
SomeString string `json:"some_string"`
}
func (parent *Parent) MarshalJSON() ([]byte, error) {
// var ii interface{}
// json.Unmarshal(&parent.ID, &ii)
// fmt.Println(ii)
ss := json.RawMessage(fmt.Sprintf("%v", parent.ID))
type Alias Parent
return json.Marshal(struct {
*Alias
ID interface{} `json:"id"`
}{
Alias: (*Alias)(parent),
ID: &ss,
})
}
func main() {
id := &IDType{Value: 1, Valid: true}
b, _ := json.Marshal(id)
fmt.Println(string(b))
parent := &Parent{ID: string(b), SomeString: "Hello"}
bb, _ := json.Marshal(parent)
fmt.Println(string(bb))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment