encoding/json unmarshal missing a field
Asked Answered
E

1

6

The following code unmarshal's the "Id", but not the "Hostname". Why? I've been staring at it for long enough now that if it's a typo I know I'll never spot it. Help please. (http://play.golang.org/p/DIRa2MvvAV)

package main

import (
    "encoding/json"
    "fmt"
)

type jsonStatus struct {
    Hostname string `json:host`
    Id       string `json:id`
}

func main() {
    msg := []byte(`{"host":"Host","id":"Identifier"}`)

    status := new(jsonStatus)

    err := json.Unmarshal(msg, &status)
    if err != nil {
        fmt.Println("Unmarshall err", err)
    }
    fmt.Printf("Got status: %#v\n", status)
}

The output I get is

Got status: &main.jsonStatus{Hostname:"", Id:"Identifier"}

where I expect

Got status: &main.jsonStatus{Hostname:"Host", Id:"Identifier"}
Elasticize answered 15/4, 2013 at 17:45 Comment(2)
Duplicate: stackoverflow.com/q/64598336/400544Gabbey
I just got the same question closed because it's a typo: stackoverflow.com/q/64598336/400544Gabbey
L
8

Your field tags are wrong. They need quotes around the alternate name.

type jsonStatus struct {
    //--------------------v----v
    Hostname string `json:"host"`
    Id       string `json:"id"`
}

Technically, you don't need a tag for the Id field at all. That's why that field was working.

DEMO: http://play.golang.org/p/tiop27jNJe

Leishmaniasis answered 15/4, 2013 at 17:45 Comment(1)
Doh, I can't believe I missed that. I also didn't realize that the key names aren't case sensitive when unmarshal'ing. Thank you!Guttural

© 2022 - 2025 — McMap. All rights reserved.