Golang JSONObject

257 views
Skip to first unread message

A JI

unread,
Dec 23, 2021, 1:23:42 PM12/23/21
to golang-nuts
Why, when the object of struct is lowercase. I can't fill it and convert to JSON ?

Kevin Chowski

unread,
Dec 23, 2021, 2:36:05 PM12/23/21
to golang-nuts
This is not a real "why", but this how json.Marshal works according to the documentation. From https://pkg.go.dev/encoding/json#Marshal:

"Struct values encode as JSON objects. Each exported struct field becomes a member of the object, using the field name as the object key, unless the field is omitted for one of the reasons given below."

(Note that struct fields that start with an uppercase letter are "exported", and fields starting with a lowercase letter is "not exported" or "unexported", as per https://go.dev/ref/spec#Exported_identifiers

I doubt it could change at this point, it would potentially cause libraries to start leaking information from structs to the json representation that people expected to stay private.

If you have a specific problem you are trying to solve, someone may be able to help if you explain what you are actually trying to achieve.

Soufien Benramdhane

unread,
Dec 23, 2021, 2:56:32 PM12/23/21
to golang-nuts
Hi A JI,

Here the documentation linked to json.Unmarshal : https://pkg.go.dev/encoding/json#Marshal

It works only exported fields. Since your field price is unexported, Marshal would just ignore it. You should probably try this: https://go.dev/play/p/49Zm1fawC9F

Using an intermediate anonymous struct could solve your issue maybe?

Shulhan

unread,
Jan 12, 2022, 12:39:01 PM1/12/22
to A JI, golang-nuts
Is not the object of struct that affect the output of JSON, but the
name of field. If the name of field start with lowercase it will
not exported by json.Marshal().

See https://go.dev/blog/json and
https://pkg.go.dev/encoding/json#Marshal for more information.

--
{ "github":"github.com/shuLhan", "site":"kilabit.info" }
Reply all
Reply to author
Forward
0 new messages