Home > Net >  How to unmarshal json with unknown field and key
How to unmarshal json with unknown field and key

Time:01-10

From front-end I got this example of json:

{
  "properties":{"unknown key": "unknown value","unknown key2": "unknown value 2"}
}

I start to parse it with map[string]interface{} but it doesn't work. Also I don't know how much this fields I can got. It can be 10 or 1.

Code:

type test struct {
    p map[string]string `json:"properties"`
}

func main() {
    var t test

    body := `
    {
        "properties":{"unknown key": "unknown value","unknown key2": "unknown value 2"}
    }
    `

    json.Unmarshal([]byte(body), &t)

    fmt.Println(t.p)
}

This code always return an empty map.

CodePudding user response:

You should export the field of the struct that should be Unmarshalled, like:

type test struct {
    P map[string]string `json:"properties"`
}

See https://go.dev/play/p/Fp91DTlrZpw

  • Related