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.
1条回答 默认 最新
- du4822 2015-03-18 00:02关注
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 }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 AT89C51控制8位八段数码管显示时钟。
- ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
- ¥15 下图接收小电路,谁知道原理
- ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
- ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
- ¥15 手机接入宽带网线,如何释放宽带全部速度
- ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
- ¥15 ETLCloud 处理json多层级问题
- ¥15 matlab中使用gurobi时报错
- ¥15 这个主板怎么能扩出一两个sata口