Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang unmarshal json map & array

Tags:

json

go

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":"[email protected]"}]`)
    c := []byte(`{"email":"[email protected]"}`)

    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: [email protected] 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

like image 750
CuriousMind Avatar asked Dec 10 '22 18:12

CuriousMind


1 Answers

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":"[email protected]"}]`)
    //b := []byte(`{"email":"[email protected]"}`)

    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)
    }

}
like image 54
yeer Avatar answered Dec 29 '22 18:12

yeer