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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀