Package [encoding/json](<https://golang.org/pkg/encoding/json/>)
in standard library provides functionality for serializing data as JSON and parsing JSON into data.
https://codeeval.dev/gist/b0ce5c49fb5e692a0daf62bcbb558f98
Both json.Marshal
and json.MarshalIndent
take [interface{}](<https://www.notion.so/kjkpublic/Empty-interface-c3315892508248fdb19b663bf8bff028>)
as first argument. We can pass any Go value, it’ll be wrapped into interface{}
with their type.
Marshaller will use reflection to inspect passed value and encode it as JSON strings.
When serializing structs, only exported fields (whose names start with capital letter) are serialized / deserialized.
In our example, fullName
is not serialized.
Structs are serialized as JSON dictionaries. By default dictionary keys are the same as struct field names.
Struct field Name
is serialized under dictionary key Name
.
We can provide custom mappings with struct tags.
We can attach arbitrary struct tags string to struct fields.
json:"age"
instructs JSON encoder / decoder to use name age
for dictionary key representing field Age
.
When serializing structs, passing the value and a pointer to it generates the same result.
Passing a pointer is more efficient because passing by value creates unnecessary copy.
json.MarshallIndent
allows for pretty-printing of nested structures. The result takes up more space but is easier to read.
https://codeeval.dev/gist/9abfbfbd4c8739650632521fd3c337ea
Parsing is the opposite of serializing.
Unlike with serializing, when parsing into structs, we must pass a pointer to struct. Otherwise json.Unmarshal
will receive and modify a copy of the struct, not the struct itself. The copy will be then discarded after returning from json.Unmarshal
.
Notice that JSON element city
was decoded into City
struct field even though the names don’t match and we didn’t provide explicit mapping with json
struct tag.