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?
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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With