Convert a nested struct to nested json dynamically golang

Viewed 110

how do i convert the following nested struct

type Details struct {
    name        string
    age         int
    address     *address
    dateOfBirth *date
}

type address struct {
    street  string
    city    string
    state   string
    country string
}

type date struct {
    day   int
    month string
    year  int
}

type StudentDetails struct {
    details *PersonalDetails
}

to a nested json of any level in golang, something like this

{
    "Student_1":{
        "name":"aaa",
        "age":20,
        "address":[{
            "street":"",
            "city":"",
            "state":"",
            "country":""
        },{
            "street":"",
            "city":"",
            "state":"",
            "country":""
        }],
        "date":{
            "day":1,
            "month":"Jan",
            "year":2000
        }
    },
    "Student_2":{
        "name":"bbb",
        "age":22,
        "address":[{
            "street":"",
            "city":"",
            "state":"",
            "country":""
        },{
            "street":"",
            "city":"",
            "state":"",
            "country":""
        }],
        "date":{
            "day":1,
            "month":"Feb",
            "year":2002
        }
    }

}

i want to build a json dynamically based on what is in this struct. The struct is build from protocol buffer. The pointer points to the struct it needs to fetch the details from. I used to reflect package to access the struct, i'm able to read through the data but not able to build the same. Any help is appreciated

1 Answers

You should construct the object and then use json.Marshal(obj)

The solution may be something like:

package main

import (
    "encoding/json"
    "fmt"
)

type User struct {
    Name        string
    Age         int
    Active      bool
    lastLoginAt string
    Address     *address
}

type address struct {
    City   string
    Street string
}

func main() {
    u, err := json.Marshal(User{Name: "Bob", Age: 10, Active: true, lastLoginAt: "today", Address: &address{City: "London", Street: "some str."}})
    if err != nil {
        panic(err)
    }
    fmt.Println(string(u))
}

The output is:

{"Name":"Bob","Age":10,"Active":true,"Address":{"City":"London","Street":"some str."}}
Related