skip to Main Content

I have a struct

type MyStruct struct {
  A string
  B int
  C string
  D int
}

And I want to convert it into a json object like this:

{
  "A": "Some string",
  "B": 1234,
  "otherStruct": {
    "C": "Other string",
    "D": 5678
  }
}

What json tags do I need to use to convert it properly?

I tried to add some json tags like this:

type MyStruct struct {
  A string  `json:"A"`
  B int     `json:"B"`
  C string  `json:"otherStruct.C"`
  D int     `json:"otherStruct.D"`
}

But it results in this:

{
  "A": "Some string",
  "B": 1234,
  "otherStruct.C": "Other string",
  "otherStruct.D": 5678
}

2

Answers


  1. If you want this JSON output using the standard Go JSON package:

    {
      "A": "Some string",
      "B": 1234,
      "otherStruct": {
        "C": "Other string",
        "D": 5678
      }
    }
    

    Then you will need to rewrite your Go structures to match the structure of the JSON. E.g:

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type (
        OtherStruct struct {
            C string
            D int
        }
    
        MyStruct struct {
            A           string
            B           int
            OtherStruct OtherStruct `json:"otherStruct"`
        }
    )
    
    func main() {
        myvar := MyStruct{
            A: "Some string",
            B: 1234,
            OtherStruct: OtherStruct{
                C: "Other string",
                D: 5678,
            },
        }
    
        jsontext, err := json.Marshal(myvar)
        if err != nil {
            panic(err)
        }
    
        fmt.Printf("%sn", jsontext)
    }
    

    This will produce:

    {
      "A": "Some string",
      "B": 1234,
      "otherStruct": {
        "C": "Other string",
        "D": 5678
      }
    }
    

    I don’t believe there’s any way with the standard tooling to have the structure of the JSON be different from the structure of your variables.

    Login or Signup to reply.
  2. While @larsks answer will work for you. Another option is to define a struct inside another struct.

    type MyStruct struct {
        A     string `json:"A"`
        B     int    `json:"B"`
        Other struct {
            C string `json:"C"`
            D int    `json:"D"`
        } `json:"otherStruct"`
    }
    

    But than you have to assign values to nested struct separately.

    data := MyStruct{
        A: "example A",
        B: 1,
    }
    
    // Set values inside Other struct
    data.Other.C = "example C"
    data.Other.D = 2
    

    This will give you same output:

    {
    "A": "example A",
    "B": 1,
    "otherStruct": {
        "C": "example C",
        "D": 2
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search