jsongostruct

Json to Struct dynamic field matching


I have the following JSON:

{
  "data": {
    "1": {
      "id": "stock1",
      "quote": {
        "USD": {
          "price": 87,
        }
      }
    },
    "14": {
      "id": "stock14",
      "quote": {
        "USD": {
          "price": 50,
        }
      }
    },
  }
}

The structs for this structure are:

type Quotes struct {
    Data struct {
        Num1 struct {
            ID    int `json:"id"`
            Quote struct {
                Usd struct {
                    Price float64 `json:"price"`
                } `json:"USD"`
            } `json:"quote"`
        } `json:"1"`
        Num14 struct {
            ID    int `json:"id"`
            Quote struct {
                Usd struct {
                    Price float64 `json:"price"`
                } `json:"USD"`
            } `json:"quote"`
        } `json:"14"`
    } `json:"data"`
}

I run the typical unmarshaling and it works:

    var quotes Quotes
    if err := json.Unmarshal(respBody, &quotes); err != nil {
        fmt.Println(err)
        os.Exit(0)
    }

However since the structure for both stocks are the same, I would like to make the structs more dynamic.

type Quotes struct {
    Data struct {
        Stock struct {
            ID    int `json:"id"`
            Quote struct {
                Usd struct {
                    Price float64 `json:"price"`
                } `json:"USD"`
            } `json:"quote"`
        } `json:"*"`
    } `json:"data"`
}

Is this possible? I know I can use reflection to dynamically add fields but I'm not sure how to go about this.


Solution

  • Why are you not simply defining Quotes as a map of key: Stock ?

    type Stock struct {
        ID    int `json:"id"`
        Quote struct {
            USD struct {
                Price float64 `json:"price"`
            } `json:"USD"`
        } `json:"quote"`
    }
    
    type Quotes struct {
        Data map[string]Stock `json:"data"`
    }