Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to unmarshal json with unknown field and key

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading