Marshal Interface{} into Json

I want to generate a json that's something like this:

{
   "A": 1,
   "B": "bVal",
   "C": "cVal"
}

But I want to keep my code generic enough that I can replace the key-pair "C" with any other type of json object that I want. I tried doing something like what I have below:

    type JsonMessage struct {
        A int `json:"A"`
        B string `json:"B,omitempty"`
        genericObj interface{} 
    }

    type JsonObj struct {
        C string `json:"C"`
    }

    func main() {
        myJsonObj := JsonObj{C: "cVal"}
        myJson := JsonMessage{A: 1, B: "bValue", genericObj: myJsonObj}

        body, _ := json.Marshal(myJson)
        fmt.Print(body)
    }

But the output is just this:

{
   "A": 1,
   "B": "bVal"
}

Is there a different way to approach this?

3

2 Answers

This is precisely why json.RawMessage exists.

Here is an example straight from the Go docs:

package main

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

func main() {
    h := json.RawMessage(`{"precomputed": true}`)

    c := struct {
        Header *json.RawMessage `json:"header"`
        Body   string           `json:"body"`
    }{Header: &h, Body: "Hello Gophers!"}

    b, err := json.MarshalIndent(&c, "", "\t")
    if err != nil {
        fmt.Println("error:", err)
    }
    os.Stdout.Write(b)

}

Here is the output:

{
    "header": {
        "precomputed": true
    },
    "body": "Hello Gophers!"
}

Go Playground:

Of course you can marshal a value before time to get the raw bytes in your case.

5
package main

import (
    "encoding/json"
    "fmt"
)

type JsonMessage struct {
    A          int    `json:"A"`
    B          string `json:"B,omitempty"`
    // simply make this field capitalized,and it will be included in the 
    // json string
    GenericObj interface{}
}

type JsonObj struct {
    C string `json:"C"`
}

func main() {
    myJsonObj := JsonObj{C: "cVal"}
    myJson := JsonMessage{A: 1, B: "bValue", GenericObj: myJsonObj}

    body, _ := json.Marshal(myJson)
    fmt.Println(string(body))
}
{"A":1,"B":"bValue","GenericObj":{"C":"cVal"}}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest