How to unmarshal json with unknown fields and keys

WBOY
Release: 2024-02-06 10:33:11
forward
674 people have browsed it

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

Question content

From the front end I got this json example:

{
  "properties":{"unknown key": "unknown value","unknown key2": "unknown value 2"}
}
Copy after login

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)
}
Copy after login

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"`
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!