json.Unmarshal returning blank structure

15,068

Your struct fields are not exported. This is because they start with a lowercase letter.

EntryCount // <--- Exported
entryCount // <--- Not exported

When I say "not exported", I mean they are not visible outside of your package. Your package can happily access them because they are scoped locally to it.

As for the encoding/json package though - it cannot see them. You need to make all of your fields visible to the encoding/json package by making them all start with an uppercase letter, thereby exporting them:

type Status struct {
    Status  string
    Node_id string
}

type Meta struct {
    To         string
    From       string
    Id         string
    EntryCount int64
    Size       int64
    Depricated bool
}

type Mydata struct {
    Metadata  Meta
    Status []Status
}

See it working on the Go Playground here

You should also reference the Golang specification for answers. Specifically, the part that talks about Exported Identifiers.

Share:
15,068

Related videos on Youtube

Kevin
Author by

Kevin

Updated on September 14, 2022

Comments

  • Kevin
    Kevin about 1 year

    I have a JSON blob that looks like this

    {
        "metadata":{
            "id":"2377f625-619b-4e20-90af-9a6cbfb80040",
            "from":"2014-12-30T07:23:42.000Z",
            "to":"2015-01-14T05:11:51.000Z",
            "entryCount":801,
            "size":821472,
            "deprecated":false
        },
        "status":[{
             "node_id":"de713614-be3d-4c39-a3f8-1154957e46a6",
             "status":"PUBLISHED"
        }]
    }
    

    and I have a little code to transform that back into go structs

    type Status struct {
        status string
        node_id string
    }
    
    type Meta struct {
        to string
        from string
        id string
        entryCount int64
        size int64
        depricated bool
    }
    
    type Mydata struct {
        met meta
        stat []status
    }
    
    var realdata Mydata
    err1 := json.Unmarshal(data, &realdata)
    if err1 != nil {
        fmt.Println("error:", err1)
    }
    fmt.Printf("%T: %+v\n", realdata, realdata)
    

    but what I see when I run this is just a zeroed structure

    main.Mydata: {met:{to: from: id: entryCount:0 size:0 depricated:false} stat:[]}
    

    I tried allocating the struct first but that also didn't work, I'm not sure why its not producing values, and its not returning an error

  • sberry
    sberry almost 9 years
    This should not be downvoted, but you should mention the json tag values for giving the marshaled json a desired name. like json:"entry_count"
  • Simon Whitehead
    Simon Whitehead almost 9 years
    Apologies. Fixed. I wrote this after heavy code discussions at work (where I am a .NET developer).
  • sten
    sten over 6 years
    I'm going to upvote this because it helped me. But man does it make me cranky.