Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

go - Adding Arbitrary fields to json output of an unknown struct

In this stackoverflow post it's explained how to add arbitrary fields to a golang struct by using it as an anonymous. This works fine if you are working with known struct types, but I'm wondering how to do the same thing when dealing with an unknown struct or interface.

I wrote the following example to demonstrate:

package main

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

type example interface{}
type Data struct {
    Name string
}

func printInterface(val interface{})    {
    example1 := struct {
        example
        Extra string
    }{
        example: val,
        Extra: "text",
    }
    json.NewEncoder(os.Stdout).Encode(example1)
}

func printStructPointer(val *Data)  {
    example2 := struct {
        *Data
        Extra string
    }{
        Data: val,
        Extra: "text",
    }
    json.NewEncoder(os.Stdout).Encode(example2)
}


func main() {
    d := Data{Name:"name"}
    fmt.Println("Example 1:")
    printInterface(&d)
    fmt.Println("Example 2:")
    printStructPointer(&d)
}

This prints the following:

Example 1:
{"example":{"Name":"name"},"Extra":"text"}
Example 2:
{"Name":"name","Extra":"text"}

I'm so assuming that I was working within printInterface how do get the JSON output to look like the JSON output of printStructPointer?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...