Home  >  Article  >  Backend Development  >  How to unmarshal json with unknown fields and keys

How to unmarshal json with unknown fields and keys

WBOY
WBOYforward
2024-02-06 10:33:11692browse

如何使用未知字段和键解组 json

Question content

From the front end I got this json example:

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

I started parsing it with map[string]interface{} but it doesn't work. I also don’t know how much I can gain in this field. 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 returns an empty map.


Correct answer


You should export the structure fields that should be unmarshalled, for example:

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

Seehttps://www.php.cn/link/eaf76caaba574ebf8e825f321c14ba29

The above is the detailed content of How to unmarshal json with unknown fields and keys. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete