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

type Nested struct {
   Something string `json:"something"`
}

I want to add elements which are not in the structs definitions without creating another struct type. For example

Struct.Extra1 = Nested{"yy"}
Struct.Nested.Extra2 = "zz"

Which will result

{
    "Value": "xx",
    "Value1": "xx",
    "Extra1": {
      "Something", "yy"
    },
    "Nest": {
      "Something": "xx",
      "Extra2": "zz"
    }
}

SOLUTION1: I thought of adding omitempty to achieve this but it makes the structs complex.

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

type Nested struct {
   Something string
   Extra2 string `json:"omitempty"`
}

SOLUTION2:

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

Is there a better solution to add nested elements which are not represented in struct datatype with json-tag support and could be used to output to user.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Thellimist
  • 3,757
  • 5
  • 31
  • 49

5 Answers5

21

If someone is not happy with the solution provided:

Try tidwall/sjson. It provides functions for quick JSON editing without having to define any structure. It saved me a bunch of time yesterday :D

Example usage:

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

// Output:
// {"name":{"last":"Smith"}}
Dhruv Batheja
  • 2,140
  • 1
  • 18
  • 16
  • 1
    Good answer. Manipulating JSON is otherwise very tedious in Go, and we should be promoting useful packages like this – mukunda Dec 28 '22 at 19:39
10

Based on this answer: Can I use MarshalJSON to add arbitrary fields to a json encoding in golang?

You could do something like (demo: 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))
}
Community
  • 1
  • 1
Fatih Arslan
  • 16,499
  • 9
  • 54
  • 55
  • 3
    Since my perfectly valid edit was rejected by the mods as "should be a comment" (even though this is a huge waste of space as a comment) - note that you don't need `json:"-"` to prevent extra from serializing, since it's not exported. – Nate Finch Jul 20 '15 at 19:21
  • 1
    Thanks @NateFinch for the info, makes sense. I'm editing it on behalf of you. – Fatih Arslan Jul 20 '15 at 19:24
3

yes. there is a type json.Raw which not a struct but []byte. you can manage it out of struct, in any marshal/unmarshal way.

UPDATE

use any way to edit json string on the fly

package main

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

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

func main() {
    s := Struct{Value1: "struct string"}
    buf, _ := json.Marshal(s)
    fmt.Println(string(buf))
    s2 := strings.ReplaceAll(string(buf), "null", `{"extra2":{"anykey":3.1415926535}}`)
    fmt.Println(s2)
}

https://play.golang.org/p/lOCxJBs5iRJ

Jiang YD
  • 3,205
  • 1
  • 14
  • 20
2

The map approach is the only sane way to do it, everything else (like json.RawMessage fields would require an extra marshalling step anyway.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
OneOfOne
  • 95,033
  • 20
  • 184
  • 185
2

if you don't want install extra package, you can change or add new values with this code :

package main

import "fmt"
import "strings"
import "encoding/json"

func main() {
    s := []byte(`{ "level1a":"aaa", "level1b":{"level2a":"bbb", "level2b":{"level3":"aaa"} } }`)
    var j interface{}
    json.Unmarshal(s, &j)
    SetValueInJSON(j, "level1a", "new value 1a")
    SetValueInJSON(j, "level1b.level2a", "new value 2a")
    SetValueInJSON(j, "level1b.level2b.level3", "new value 3")
    SetValueInJSON(j, "level1b.level2c", "new key")
    s,_ = json.Marshal(j)
    fmt.Println(string(s))
    // result: {"level1a":"new value 1a","level1b":{"level2a":"new value 2a","level2b":{"level3":"new value 3"},"level2c":"new key"}}

}

func SetValueInJSON(iface interface{}, path string, value interface{}) interface{} {
    m := iface.(map[string]interface{})
    split := strings.Split(path, ".")
    for k, v := range m {
        if strings.EqualFold(k, split[0]) {
            if len(split) == 1 {
                m[k] = value
                return m
            }
            switch v.(type) {
            case map[string]interface{}:
                return SetValueInJSON(v, strings.Join(split[1:], "."), value)
            default:
                return m
            }
        }
    }
    // path not found -> create
    if len(split) == 1 {
        m[split[0]] = value
    } else {
        newMap := make(map[string]interface{})
        newMap[split[len(split)-1]] = value
        for i := len(split) - 2; i > 0; i-- {
            mTmp := make(map[string]interface{})
            mTmp[split[i]] = newMap
            newMap = mTmp
        }
        m[split[0]] = newMap
    }
    return m
}
asimov
  • 71
  • 4
  • That is pretty nice. What happens if there is an slice in the nested object. It solves this exact problem, I am just wondering about a more generic solution/different scenario – Jaspreet Singh Feb 16 '22 at 02:06