vodolaz095
vodolaz095

Reputation: 6986

Golang - unable to parse JSON

I've started learning GO, and i have encountered this issue. I have this code

package main

import (
  "log"
  "encoding/json"
)


func main(){
  type Weather struct {
    name string
    cod float64
    dt float64
    id float64
  }

  var rawWeather = []byte(`{"name":"London","cod":200,"dt":1407100800,"id":2643743}`)
  var w Weather
  err := json.Unmarshal(rawWeather, &w)
  if err != nil {
    log.Fatalf("%s : while parsing json", err)
  }
  log.Printf("%+v\n",w)
}

when i run it, it shows this

[nap@rhel projects]$ go run euler.go 
{name: cod:0 dt:0 id:0}

So, the JSON is not parsed into the weather struct.

Any ideas, why do this happens like this?

Upvotes: 3

Views: 1969

Answers (3)

evanmcdonnal
evanmcdonnal

Reputation: 48086

This is because Weather does not export any fields. This;

type Weather struct {
   name string
   cod float64
   dt float64
   id float64
}

Needs to be;

type Weather struct {
   Name string
   Cod float64
   Dt float64
   Id float64
}

If a field is not exported then the json package will not be able to access it. You can find more information about it here http://blog.golang.org/json-and-go but the short version is;

" The json package only accesses the exported fields of struct types (those that begin with an uppercase letter). Therefore only the the exported fields of a struct will be present in the JSON output."

Upvotes: 1

Simon Whitehead
Simon Whitehead

Reputation: 65079

You need to capitalise your struct fields. E.g:

Name string
Cod  float64
// etc..

This is because they are not visible to the json package when attempting to unmarshal.

Playground link: http://play.golang.org/p/cOJD4itfIS

Upvotes: 7

vodolaz095
vodolaz095

Reputation: 6986

By quessing, i found, that this code works:

package main

import (
  "fmt"
  "encoding/json"
//  "net/html"
)


func main(){
  type Weather struct {
    Name string
    Cod float64
    Dt float64
    Id float64
  }

  var rawWeather = []byte(`[{"name":"London","cod":200,"dt":1407100800,"id":2643743}]`)
  var w []Weather
  err := json.Unmarshal(rawWeather, &w)
  if err != nil {
    fmt.Println("Some error", err)
  }
  fmt.Printf("%+v\n",w)
}

So, the struct field names have to be Capitalized to work properly!

Upvotes: 0

Related Questions