Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marshal interface{} into json

Tags:

json

encoding

go

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?

like image 584
J.Doe Avatar asked Jun 21 '17 00:06

J.Doe


People also ask

What is marshal in JSON?

JSON has 3 basic types: booleans, numbers, strings, combined using arrays and objects to build complex structures. Go's terminology calls marshal the process of generating a JSON string from a data structure, and unmarshal the act of parsing JSON to a data structure.

How do I encode JSON in Golang?

To encode JSON data we use the Marshal function. Only data structures that can be represented as valid JSON will be encoded: JSON objects only support strings as keys; to encode a Go map type it must be of the form map[string]T (where T is any Go type supported by the json package).

What is JSON encoding?

jsonencode encodes a given value to a string using JSON syntax. The JSON encoding is defined in RFC 7159. This function maps Terraform language values to JSON values in the following way: Terraform type. JSON type.

How do I read JSON data in Golang?

json is read with the ioutil. ReadFile() function, which returns a byte slice that is decoded into the struct instance using the json. Unmarshal() function. At last, the struct instance member values are printed using for loop to demonstrate that the JSON file was decoded.


1 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: https://play.golang.org/p/skYJT1WyM1C

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

like image 111
squiguy Avatar answered Oct 19 '22 20:10

squiguy