Skip to content

json.Marshal returns {} for a struct when struct vars start with lowercase #2131

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
gopherbot opened this issue Aug 4, 2011 · 1 comment
Closed

Comments

@gopherbot
Copy link
Contributor

by hendrik.demolder:

What steps will reproduce the problem?:

package main 
import (
        "json"
        "fmt" 
) 
type Message struct { 
        test string
        test2 string
}


func main() {  
        var m  = Message{"t1", "t22"}
        output, _ := json.Marshal(m) 
        fmt.Println(string(output))
} 




What is the expected output?:

{"Test":"t1","Test2":"t22"}


What do you see instead?:
{}

Which compiler are you using (5g, 6g, 8g, gccgo)?
6g

Which operating system are you using?
linux/Fedora 

Which revision are you using?  (hg identify)
d5785050f61d (release-branch.r59) release/release.r59

Additional remarks:

By changing Message to:

type Message struct { 
        Test string
        Test2 string
}

It works correclty: {"Test":"t1","Test2":"t22"}
@rsc
Copy link
Contributor

rsc commented Aug 4, 2011

Comment 1:

Because Unmarshal cannot write to lower case fields,
Marshal ignores them for symmetry.  They are only
exposed by reflect for easier debugging with fmt.Print.
If you need a field with a lower-case name in the
json output you can write
type Message struct {
    Test string  `json:"test"`
}
Russ

Status changed to WorkingAsIntended.

@golang golang locked and limited conversation to collaborators Jun 24, 2016
This issue was closed.
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants