Golang的JSON迭代不支持索引。

huangapple go评论79阅读模式
英文:

golang json iterate not supporting indexing

问题

我在使用golang解析json时遇到了问题。
我使用了一些代码将json解析为map[string]interface{}{},但是当我尝试遍历嵌套字段时,会触发错误(type interface {} does not support indexing)

我想获取以下信息:

  • 遍历每个response->blogs,然后获取位于response->posts->blog_n->photos->original_size中的original_size照片的URL
  • meta->status
  • response->blog->total_postsresponse->blog->name

这是一个指向playground的链接。
谢谢你的帮助!

英文:

I've got a problem with my json parsing in golang.
I used some code to parse the json into a map[string]interface{}{} but when I try to iterate through a nested field, the error (type interface {} does not support indexing) is triggered.

I'd like to get the following informations :

  • iterate through each response->blogs and then get the url of original_size photo that lays in response->posts->blog_n->photos->original_size
  • meta->status
  • response->blog->total_posts and response->blog->name

Here's a link to a playground
Thank you for your help !

答案1

得分: 3

你想使用map有什么原因吗?要进行你所说的带有映射的索引,我认为你还需要使用嵌套映射

你考虑过使用嵌套结构体了吗?可以参考这里的链接:https://stackoverflow.com/questions/25966567/go-unmarshal-nested-json-structure 和 https://stackoverflow.com/questions/21268000/unmarshaling-nested-json-objects-in-golang

对于你的JSON数据,这是一个示例——工作但有限的struct。Go会忽略你不使用的字段。

func main() {
    // 为JSON创建映射
    data := &Header{}

    // 解析/反序列化JSON
    err := json.Unmarshal([]byte(input), &data)

    if err != nil {
        panic(err)
    }

    fmt.Printf("%+v\n", m)
}

type Header struct {
    Response struct {
        Blog struct {
            Title string `json:"title"`
        } `json:"blog"`
        Posts []struct {
            Id int64 `json:"id"`
        } `json:"posts"`
    } `json:"response"`
}

要让Go按照你的要求处理JSON,你需要了解JSON及其与Go类型的关系。

注意:在JSON中,slicestructobjectarray,即[{..},{..}]

在Go中,**只有公开的(exported)**字段才会被填充。

英文:

Is there a reason you want to use a map? To do the indexing you're talking about, with maps, I think you would need nested maps as well.

Have you considered using nested structs, as described here, https://stackoverflow.com/questions/25966567/go-unmarshal-nested-json-structure and https://stackoverflow.com/questions/21268000/unmarshaling-nested-json-objects-in-golang ?

For your JSON data, here is a sample -- working but limited -- struct. Go will ignore the fields you don't use.

func main() {
    //Creating the maps for JSON
    data := &Header{}

    //Parsing/Unmarshalling JSON encoding/json
    err := json.Unmarshal([]byte(input), &data)

    if err != nil {
	    panic(err)
    }

    fmt.Printf("%+v\n", m)
}
type Header struct {
    Response struct { 
        Blog struct {
            Title string `json:"title"`
        } `json:"blog"`
        Posts []struct {
            Id int64 `json:"id"`
        } `json:"posts"`
    } `json:"response"`
}

To get JSON with Go to do what you want, you have to brush up on JSON and it's relation to Go types.

Notice posts:
slices of structs are, in JSON, arrays of objects, [{..},{..}]

In Go, only exported fields will be filled.

答案2

得分: 1

这个错误出现是因为你的 map[key-type]val-type,而你尝试获取的值是嵌套的 map。

你可以使用类型断言来获取值。

result := m["response"].(map[string]interface{})
fmt.Printf("%+v\n", result["blog"])
英文:

this error appear because your map[key-type]val-type, and you to try get value as nested map.

you can use Type Assertion to get value.

result := m["response"].(map[string]interface{}) 
fmt.Printf("%+v\n", result["blog"])

huangapple
  • 本文由 发表于 2017年1月20日 01:52:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/41748478.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定