简体   繁体   English

如何解组json

[英]How to unmarshal json

I am using http.Get in go to a url which results in the following {"name":"cassandra","tags":["2.2.6","latest"]} that means it behaves like map[string]string for the name field but in the tags it behaves like map[string][]string so how can I unmarshal this in Go? 我正在使用http.Get进入一个导致以下{“ name”:“ cassandra”,“ tags”:[“ 2.2.6”,“ latest”]}的网址,这意味着它的行为类似于map [string]名称字段的字符串,但是在标签中,它的行为类似于map [string] [] string,因此如何在Go中解组? I tried using map[string][]string but it did not work 我尝试使用map [string] [] string,但是没有用

map_image_tags := make(map[string][]string)    
res2, err := http.Get(fmt.Sprintf("%s/v2/%s/tags/lists", sconf.RegistryConf.url, Images[i]))
        if err != nil {
            w.WriteHeader(500)
            log.Errorf("could not get tags: %s", err)
            return
        }
        log.Debugf("OK")
        js2, err := ioutil.ReadAll(res2.Body)
        if err != nil {
            w.WriteHeader(500)
            log.Errorf("could not read body: %s", err)
            return
        }
        log.Debugf("OK")
        err = json.Unmarshal(js2, map_image_tags)
        if err != nil {
            w.WriteHeader(500)
            log.Errorf("could not unmarshal json: %s", err)
            return
        }

I am getting this log error: could not unmarshal json: invalid character 'p' after top-level value 我收到此日志错误:无法解组json:顶级值后的无效字符'p'

To read a json value like {"name":"cassandra", "tags":["2.2.6","latest"] , you can use a struct defined as: 要读取诸如{"name":"cassandra", "tags":["2.2.6","latest"]等json值,可以使用以下结构定义:

type mapImageTags struct {
    Name string `json:"name"`
    Tags []string `json:"tags"` // tags is a slice (array) of strings
}

To unmarshal JSON data, 要解组JSON数据,

m := mapImageTags{}
err = json.Unmarshal(js2, &m)

A simple map[string]string wont help in this case. 在这种情况下,简单的map[string]string无济于事。

Try map[string]interface{} , note that this method forces any numbers to float and in general not recommended when your json is complex. 尝试map[string]interface{} ,请注意,此方法会强制任何数字float并且在json复杂时通常不建议这样做。 abhink 's answer is the recommended way. abhink的答案是推荐的方法。

If the structure of json data is dynamic you can unmarshal tags into map[string]interface{} : 如果json数据的结构是动态的,则可以将tags解组到map[string]interface{}

var encodedTags map[string]interface{}
result := json.Unmarshal([]byte(image_tags), &encodedTags)

Then you can use type assertion to unmarshal the content of tags : 然后,您可以使用类型断言来解组tags的内容:

var tags []interface{}
result = json.Unmarshal([]byte(encodedTags["tags"].(string)), &tags)

And here is a full working example on Go Playground . 这是Go Playground上的完整示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM