Home > front end >  Why do these golang JSON Unmarshal examples behave differently?
Why do these golang JSON Unmarshal examples behave differently?

Time:08-20

I'm puzzled by the following behavior and I'm trying to figure out what to do about it. Can anyone please explain to me why these behave differently? Why isn't web_url read into Bar.Url?

package main

import (
    "encoding/json"
    "fmt"
    "testing"
)

type Foo struct {
    Web_url string
}

type Bar struct {
    Url string `json:'web_url'`
}

func TestJson(t *testing.T) {
    j := []byte(`{"web_url":"xyz"}`)

    f := &Foo{}
    err := json.Unmarshal(j, f)
    fmt.Printf("err: %v, f: % v\n", err, f)


    b := &Bar{}
    err = json.Unmarshal(j, b)
    fmt.Printf("err: %v, b: % v\n", err, b)
}

Results...

go test -v -run TestJson
=== RUN   TestJson
err: <nil>, f: &{Web_url:xyz}
err: <nil>, b: &{Url:}
--- PASS: TestJson (0.00s)
PASS
ok      gitlabsr.nuq.ion.nokia.net/sr/linux/gitlab-tools/internal/junk

CodePudding user response:

Using single quotes in struct tag definition caused this error.

package main

import (
    "encoding/json"
    "fmt"
    "testing"
)

type Foo struct {
    Web_url string
}

type Bar struct {
    Url string `json:"web_url"`
}

func TestJson(t *testing.T) {
    j := []byte(`{"web_url":"xyz"}`)

    f := &Foo{}
    err := json.Unmarshal(j, f)
    fmt.Printf("err: %v, f: % v\n", err, f)


    b := &Bar{}
    err = json.Unmarshal(j, b)
    fmt.Printf("err: %v, b: % v\n", err, b)
}
  • Related