2

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
  • First of all, you must have exported struct fields. Then tell us what you have done already that didn't work. Did you try to encoding/json package to Marshal your struct? If yes, what was the problem with it? Commented Jun 23, 2022 at 21:47

1 Answer 1

2

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."}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.