Skip to content

Instantly share code, notes, and snippets.

@SCP002
Last active March 15, 2022 22:04
Show Gist options
  • Save SCP002/673205dc6429186c4794d4d9b44bde35 to your computer and use it in GitHub Desktop.
Save SCP002/673205dc6429186c4794d4d9b44bde35 to your computer and use it in GitHub Desktop.
Golang: Marshal & Unmarshal partially known / dynamic JSON. Using structs (type safe).
// To stop json.Marshal from using HTMLEscape and adding trailing newline, see:
// https://github.com/SCP002/jsonexraw
package main
import (
"fmt"
json "github.com/yaegashi/jsonex.go/v1"
)
type TopStruct struct {
TopKnownKey int `json:"topKnownKey"`
NestedKnownArray []NestedStruct `json:"nestedKnownArray"`
ExcludedKnownKey int `json:"-"` // Field sample for internal needs, excluded from JSON processing.
Unknown map[string]interface{} `json:"-" jsonex:"true"` // All unknown fields go here.
}
type NestedStruct struct {
NestedKnownKey int `json:"nestedKnownKey"`
ExcludedKnownKey int `json:"-"` // Field sample for internal needs, excluded from JSON processing.
Unknown map[string]interface{} `json:"-" jsonex:"true"` // All unknown fields go here.
}
func main() {
const input string = `
{
"topKnownKey": 1,
"topUnknownKey": 2,
"nestedKnownArray": [
{
"nestedKnownKey": 3,
"nestedUnknownKey": 4
},
{
"nestedKnownKey": 5,
"nestedUnknownKey": 6
}
],
"nestedUnknownArray": [
{
"nestedKnownKey": 7,
"nestedUnknownKey": 8
}
]
}
`
// Decode.
ts := TopStruct{}
err := json.Unmarshal([]byte(input), &ts)
if err != nil {
panic(err)
}
// Modify.
ts.TopKnownKey = 100
ts.ExcludedKnownKey = 200
ts.NestedKnownArray[0].NestedKnownKey = 300
ts.NestedKnownArray[0].ExcludedKnownKey = 400
// Encode.
out, err := json.MarshalIndent(&ts, "", " ")
if err != nil {
panic(err)
}
// Print output.
fmt.Print(string(out))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment