AlekseySychev
@AlekseySychev
Программирую в небольшой веб-студии.

Не могу понять логику работы json.Marshal. Почему на выходе пустой объект?

Подскажите пожалуйста. Есть вот такой код:
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)

Скрин
1a63cbf7c2.jpg


почему result = {}, а не {"test message"}
Скрин
1b07437fb4.jpg
  • Вопрос задан
  • 222 просмотра
Решения вопроса 2
EvgenyMamonov
@EvgenyMamonov Куратор тега Go
Senior software developer, system architect
Тут дело в том, что поле `text` у вас написано с маленькой буквы, а значит оно не экпортируемое.
Именно по этому такой результат. А когда вы напишите его с большой буквы - всё заработает как вы ожидаете.
Ответ написан
Комментировать
AlekseySychev
@AlekseySychev Автор вопроса
Программирую в небольшой веб-студии.
type Test struct {
	Text string `json:"test"`
}

Вот так работает. Ответ нашел тут: Ссылка
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
@alexxsilvers
Как гласит дока - 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 the exported fields of a struct will be present in the JSON output.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы