是否可以部分解码和更新JSON? (去) [英] Is it possible to partially decode and update JSON? (go)

查看:99
本文介绍了是否可以部分解码和更新JSON? (去)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要解码和更新json对象的特定值. 问题是我不知道对象的完整结构. encoding/json包忽略"/截断了结构中未提供的字段,因此对这些字段进行编码会丢失. 我想知道是否有可能仅解组我知道的结构,对其进行更新然后再对它进行封送,而不会截断/删除未知的结构/信息.

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.

推荐答案

似乎有可能.

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

}

这篇关于是否可以部分解码和更新JSON? (去)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆