A
A
Alexander Shpak2015-09-16 06:11:04
go
Alexander Shpak, 2015-09-16 06:11:04

How to get JSON from a structure in Golang with only given fields?

Let's say there is a structure

type SampleStruct struct {
    Foo string `json:"foo"`
    Bar string `json:"bar"`
}
example := &SampleStruct{
    Foo: "foo foo foo",
    Bar: "bar bar bar",
}

Suppose there is a need to receive JSON data sometimes in its entirety, and sometimes not entirely from the structure, but partially, for example, by making Marshal we will get something like this at the output: {foo: "foo foo foo", bar: "bar bar bar"}, and if you need to get JSON with only part of the fields, for example, to get this: {foo: "foo foo foo"}? Is the way out in the creation of additional structures?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kirill, 2015-09-16
@shpaker

Bar string `json:"bar,omitempty"`
if Bar is empty, then it will not be in json

O
Oscar Django, 2015-09-16
@winordie

type SampleStruct struct { 
    Foo string `json:"foo"` 
    Bar string `json:"-"` 
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question