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 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用