A
A
Alexey Sychev2019-12-19 14:38:52
go
Alexey Sychev, 2019-12-19 14:38:52

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)

Screen
1a63cbf7c2.jpg

why result = {} and not {"test message"}
Screen
1b07437fb4.jpg

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Mamonov, 2019-12-19
@AlekseySychev

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.

A
alexxsilvers, 2019-12-19
@alexxsilvers

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 question

Ask a Question

731 491 924 answers to any question