Last active
March 15, 2022 22:04
-
-
Save SCP002/673205dc6429186c4794d4d9b44bde35 to your computer and use it in GitHub Desktop.
Golang: Marshal & Unmarshal partially known / dynamic JSON. Using structs (type safe).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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