go - Golang unmarshal json map & array -


after reading json , go, understand basics of decoding json in go are. however, there problem input json can map & array of maps.

consider 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 b", v)     default:         fmt.println("no type found")     }      json.unmarshal(c, &m)     switch v := m.(type) {     case map[string]interface{}:         fmt.println("this c", v)     default:         fmt.println("no type found")     }  } 

now, how value email: example@test.com in both cases(b & c)

question:

  1. if json array, want loop on each & print email.
  2. if json map, want print email directly

play: http://play.golang.org/p/upofxorqwl

in experience, using interface{} handle json decoding may cause strange problem, tend avoid it. although there ways achieve using reflect package.

here solution problem base on origin solution, hope 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)         }         _, m := range ms {             fmt.println(m.email)         }     } else {         fmt.println(m.email)     }  } 

Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

c++ - Clear the memory after returning a vector in a function -

erlang - Saving a digraph to mnesia is hindered because of its side-effects -