3

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?

1
  • Make the struct fields as exported. Commented Oct 3, 2021 at 15:06

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

Comments

1

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."

Comments

0

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!

2 Comments

Capitalizing its properties means give them a "public visibility" in an instance scope, I suppose... Am I wrong or sounds weird a struct defined inside the main function?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.