Golang修改没有struct的json

The*_*ist 11 json go

type Struct struct {
   Value  string `json:"value"`
   Value1 string `json:"value_one"`
   Nest   Nested `json:"nest"`
}

type Nested struct {
   Something string `json:"something"`
}
Run Code Online (Sandbox Code Playgroud)

我想添加不在结构定义中的元素而不创建另一个结构类型.例如

Struct.Extra1 = Nested{"yy"}
Struct.Nested.Extra2 = "zz"
Run Code Online (Sandbox Code Playgroud)

这将导致

{
    "Value": "xx",
    "Value1": "xx",
    "Extra1": {
      "Something", "yy"
    },
    "Nest": {
      "Something": "xx",
      "Extra2": "zz"
    }
}
Run Code Online (Sandbox Code Playgroud)

SOLUTION1: 我想添加omitempty来实现这一点,但它使结构变得复杂.

type Struct struct {
   Value  string
   Value1 string
   Nest   Nested
   Extra1 Nested `json:"omitempty"`
}

type Nested struct {
   Something string
   Extra2 string `json:"omitempty"`
}
Run Code Online (Sandbox Code Playgroud)

溶液2:

myextras := make(map[string]interface{})
// get Struct.Nested in map[string]interface{} format
myextras = Struct.Nest
myextras["Extra2"] = "zz"

// get Struct in map[string]interface{} format
struct["Nest"] = myextras
struct["Extra1"] = Nested{"yy"}

// solves the problem with lots of type casting but doesn't support json tag naming
Run Code Online (Sandbox Code Playgroud)

是否有更好的解决方案来添加嵌套元素,这些元素在结构数据类型中没有用json-tag支持表示,并且可以用于输出给用户.

Dhr*_*eja 7

如果有人提供的解决方案不满意

尝试tidwall/sjson。它提供了无需定义任何结构即可快速编辑 JSON 的功能。昨天它为我节省了很多时间:D

用法示例:

value, _ := sjson.Set(`{"name":{"last":"Anderson"}}`, "name.last", "Smith")
println(value)

// Output:
// {"name":{"last":"Smith"}}
Run Code Online (Sandbox Code Playgroud)


Fat*_*lan 6

根据这个答案:我可以使用MarshalJSON将任意字段添加到golang中的json编码吗?

你可以做类似的事情(演示:http://play.golang.org/p/dDiTwxhoNn):

package main

import (
    "encoding/json"
    "fmt"
    "log"
)

type Book struct {
    Title  string
    Author string

    // extra is used for additional dynamic element marshalling
    extra func() interface{}
}

type FakeBook Book

func (b *Book) SetExtra(fn func() interface{}) {
    b.extra = fn
}

func (b *Book) MarshalJSON() ([]byte, error) {
    if b.extra == nil {
        b.extra = func() interface{} { return *b }
    }

    return json.Marshal(b.extra())
}

func main() {
    ms := &Book{
        Title:  "Catch-22",
        Author: "Joseph Heller",
    }

    ms.SetExtra(func() interface{} {
        return struct {
            FakeBook
            Extra1 struct {
                Something string `json:"something"`
            } `json:"extra1"`
        }{
            FakeBook: FakeBook(*ms),
            Extra1: struct {
                Something string `json:"something"`
            }{
                Something: "yy",
            },
        }
    })

    out, err := json.MarshalIndent(ms, "", "  ")
    if err != nil {
        log.Fatalln(err)
    }
    fmt.Println(string(out))

    mb := &Book{
        Title:  "Vim-go",
        Author: "Fatih Arslan",
    }

    mb.SetExtra(func() interface{} {
        return struct {
            FakeBook
            Something string `json:"something"`
        }{
            FakeBook:  FakeBook(*mb),
            Something: "xx",
        }
    })

    out, err = json.MarshalIndent(mb, "", "  ")
    if err != nil {
        log.Fatalln(err)
    }
    fmt.Println(string(out))

    mc := &Book{
        Title:  "Another-Title",
        Author: "Fatih Arslan",
    }

    out, err = json.MarshalIndent(mc, "", "  ")
    if err != nil {
        log.Fatalln(err)
    }
    fmt.Println(string(out))
}
Run Code Online (Sandbox Code Playgroud)

  • 由于我完全有效的编辑被 mods 拒绝为“应该是评论”(即使这是作为评论的巨大空间浪费) - 请注意,您不需要 `json:"-"` 来防止额外的序列化,因为它没有导出。 (2认同)