Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

json - Capitals in struct fields

I'm using this library to access CouchDB (cloudant to be specific) "github.com/mikebell-org/go-couchdb" and I've noticed a problem.

When I go to add a file to the database and pass in a struct, only the fields of the struct which started with a capital letter get added.

For example

type Person struct {
    name string
    Age  int
}

func main() {
    db, _ := couchdb.Database(host, database, username, password)
    joe := Person{
        name: "mike",
        Age:  190,
    }
    m, _ := db.PostDocument(joe)
}

In this case, only the "age" field got updated and inserted into my database.

I've noticed this problem in another case also - when I'm doing something like this :

type Sample struct {
    Name string
    age  int 
}


joe := Sample{
    Name: "xx",
    age:  23,
}

byt, _ := json.Marshal(joe)

post_data := strings.NewReader(string(byt))
fmt.Println(post_data)

in this case, only Name would be printed out :

output : &{{"Name":"xx"} 0 -1}

Why is this? and If I would like to have a field with a lowercase and be inside the database, is that possible?

question from:https://stackoverflow.com/questions/24837432/capitals-in-struct-fields

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is because only fields starting with a capital letter are exported, or in other words visible outside the curent package (and in the json package in this case).

Here is the part of the specifications refering to this: http://golang.org/ref/spec#Exported_identifiers

Still, you can unmarshall json fields that do no start with a capital letters using what is called "tags". With the json package, this is the syntax to use:

type Sample struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

Refer to the documentation for more information about this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...