Answer the question
In order to leave comments, you need to log in
I can't understand the logic of json.Marshal. Why is the output an empty object?
Tell me please. There is this code:
type Test struct {
text string `json:"test"`
}
var test Test
test.text = "test message"
result, err := json.Marshal(test)
log.Println(test)
log.Println(result)
log.Println(err)
Answer the question
In order to leave comments, you need to log in
Here the point is that the `text` field is written with a small letter, which means it is not exportable.
That is why this is the result. And when you write it with a capital letter, everything will work as you expect.
As the doc says - https://blog.golang.org/json-and-go
only data structures that can be represented as valid JSON will be encoded:
JSON objects only support strings as keys; to encode a Go map type it must be of the form map[string]T (where T is any Go type supported by the json package).
Channel, complex, and function types cannot be encoded.
Cyclic data structures are not supported; they will cause Marshal to go into an infinite loop.
Pointers will be encoded as the values they point to (or 'null' if the pointer is nil).
The json package only accesses the exported fields of struct types (those that begin with an uppercase letter). Therefore, only the exported fields of a struct will be present in the JSON output.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question