dongmaonao0505 2018-02-26 22:01
浏览 52
已采纳

从JSON中的JSON数组中提取值(以及为什么不反映和编译错误报告同一类型)

I am having trouble unmarshalling some JSON in Go. In the below code, I want to be able to extract the value of "c" ("Apple", "Berry") from the JSON (<- main goal/question). What has me particularly confused is when I tried to index into the v array(?), I get the error: invalid operation: v[0] (type interface {} does not support indexing).

This is what brought me to using reflect and looking at the type of the variable, which as you can see below is "[]interface {}", even if I assert it to be "interface {}". Of note, if I make the line q := interface{}(v) into q := []interface{}(v), I get: cannot convert v (type interface {}) to type []interface {}: need type assertion. What am I missing? Why does reflect say it is "[]interface {}" but errors say it is "interface {}"? (<- secondary question / help me understand)

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
)

func main() {
    data := []byte("{ \"a\" : { \"b\" : [ { \"n\" : 100, \"c\" : \"Apple\", \"m\" : 1, \"bool\" : false }, { \"n\" : 101, \"c\" : \"Berry\", \"m\" : 2, \"bool\" : false } ] }, \"foo\" : false, \"bar\" : \"foobar\" }")
    var a map[string]interface{}

    _ = json.Unmarshal(data, &a)

    b := a["a"].(map[string]interface{})
    for i, v := range b {
        fmt.Println(i, reflect.TypeOf(v))
        q := interface{}(v)
        fmt.Println(q, reflect.TypeOf(q))
    }

}

Output:

b []interface {}
[map[m:1 bool:false n:100 c:Apple] map[c:Berry m:2 bool:false n:101]] []interface {}
  • 写回答

1条回答 默认 最新

  • dqsk4643 2018-02-27 00:00
    关注

    Instead of attempting to unmarshal the json into an interface, you can create specific types to model what the data will be. See the example code below.

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    func main() {
        data := []byte("{ \"a\" : { \"b\" : [ { \"n\" : 100, \"c\" : \"Apple\", \"m\" : 1, \"bool\" : false }, { \"n\" : 101, \"c\" : \"Berry\", \"m\" : 2, \"bool\" : false } ] }, \"foo\" : false, \"bar\" : \"foobar\" }")
    
        type c struct {
            N int    `json:"n"`
            C string `json:"c"`
            M int    `json:"m"`
            B bool   `json:"bool"`
        }
        type b struct {
            C   []c    `json:"b"`
            Foo bool   `json:"foo"`
            Bar string `json:"bar"`
        }
        type a struct {
            A b `json:"a"`
        }
    
    
        var result a
        if err := json.Unmarshal(data, &result); err != nil {
            panic(err.Error())
        }
    
        fmt.Printf("%+v", result)
    }
    

    Link to playground.

    output: {A:{C:[{N:100 C:Apple M:1 B:false} {N:101 C:Berry M:2 B:false}] Foo:false Bar:}}

    Note that the type members are capitalised - this is required for the json unmarshaling to work correctly.

    Once the json is unmarshaled into your types, you can refer to the members as you'd expect:

        for _, v := range result.A.C {
            fmt.Println(v)
        }
    

    output:

    {100 Apple 1 false}
    {101 Berry 2 false}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。
  • ¥20 在easyX库下编写C语言扑克游戏跑的快,能实现简单的人机对战