I need to decode and update only a specific value of a json object. The issue is that I don't know the full structure of the object. The encoding/json package "ignores"/truncates the fields not provided in the struct so on encoding these fields are lost. I'm wondering if it's possible to unmarshal only the structure I know, update it and then marshal it without to truncate/remove the unknown structure/information.
It seems it's possible.
package main
import (
"encoding/json"
"fmt"
"log"
)
func main() {
type Color struct {
Space string
Point json.RawMessage // delay parsing until we know the color space
}
type RGB struct {
R uint8
G uint8
B uint8
}
type YCbCr struct {
Y uint8
Cb int8
Cr int8
}
var j = []byte(`
{"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10}}`)
var colors Color
err := json.Unmarshal(j, &colors)
if err != nil {
log.Fatalln("error:", err)
}
colors.Space = "no-space"
b, err := json.Marshal(&colors)
if err != nil {
panic(err)
}
fmt.Printf("b is now %s", b)
return
}