Home > OS >  Unmarshal json that has multile type data without key
Unmarshal json that has multile type data without key

Time:11-08

Let say I have json like this:

{
      "a": [
            [
            "aaa",
            15
            ],
            [
            "bbb",
            11
            ]
        ]
    }

I have this code :

func main() {
    XJson := `
    {
      "a": [
            [
            "aaa",
            15
            ],
            [
            "bbb",
            11
            ]
        ]
    }`

    var Output StructJson

    json.Unmarshal([]byte(XJson), &Output)

    fmt.Println(Output)
}

type StructJson struct {
    [][]string `json:"a"`  //wrong because have 15 and 11 have int type data
    ///what must i do in here?
}



How to unmarshal that? I mean, that "aaa" and "bbb" have type data string, 15 and 11 have type data integer. If i use that "wrong" struct, output is

{[[aaa ] [bbb ]]}

CodePudding user response:

@ekomonimo as @colm.anseo mentioned, for solving this sort of problems we can use the interface{}

Here how to use it:

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
)

func main() {
    XJson := `
    {
      "a": [
            [
            "aaa",
            15
            ],
            [
            "bbb",
            11
            ]
        ]
    }`

    var Output StructJson

    json.Unmarshal([]byte(XJson), &Output)

    fmt.Println("Output:", Output)
    // Prints: aaa string
    fmt.Println("Data on path Output.A[0][0]:", Output.A[0][0], reflect.TypeOf(Output.A[0][0]))
    // Prints: 15 float64
    fmt.Println("Data on path Output.A[0][1]:", Output.A[0][1], reflect.TypeOf(Output.A[0][1]))
}

type StructJson struct {
    A [][]interface{} `json:"a"`
}
  • Related