-2

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
1
  • 3
    The syntax for struct tags uses double quotes. Run go vet.
    – JimB
    Aug 18, 2022 at 20:08

1 Answer 1

4

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)
}
1
  • Interesting. The example I was copying using single quotes. Thank you! Aug 19, 2022 at 17:49

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.