duanbeng6709 2016-02-29 04:05
浏览 46
已采纳

Golang解组JSON地图和数组

After reading JSON and Go, I do understand the basics of decoding json in Go are. However, there this problem where that input json can be sometimes a map & sometimes an array of maps.

consider the following problem:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    b := []byte(`[{"email":"example@test.com"}]`)
    c := []byte(`{"email":"example@test.com"}`)

    var m interface{}

    json.Unmarshal(b, &m)
    switch v := m.(type) {
    case []interface{}:
        fmt.Println("this is b", v)
    default:
        fmt.Println("No type found")
    }

    json.Unmarshal(c, &m)
    switch v := m.(type) {
    case map[string]interface{}:
        fmt.Println("this is c", v)
    default:
        fmt.Println("No type found")
    }

}

Now, how to I get to the value email: example@test.com in both cases(b & c)

Question:

  1. If json is an array, I want to loop over each & print email.
  2. if json is an map, I want to print email directly

Play: http://play.golang.org/p/UPoFxorqWl

  • 写回答

5条回答 默认 最新

  • doumi4974 2016-02-29 05:49
    关注

    In my experience, using interface{} to handle json decoding may cause some strange problem, which I tend to avoid it. Although there are ways to achieve it using the reflect package.

    Here is a solution for you problem base on your origin solution, hope it helps.

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Item struct {
        Email string `json:email`
    }
    
    func main() {
        b := []byte(`[{"email":"example_in_array@test.com"}]`)
        //b := []byte(`{"email":"example@test.com"}`)
    
        var m = &Item{}
        var ms = []*Item{}
        err := json.Unmarshal(b, &m)
        if err != nil {
            err = json.Unmarshal(b, &ms)
            if err != nil {
                panic(err)
            }
            for _, m := range ms {
                fmt.Println(m.Email)
            }
        } else {
            fmt.Println(m.Email)
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭