AppDividend
Latest Code Tutorials

Golang JSON Example | How To Use JSON With Go

0

Golang JSON Example is today’s topic. When it comes to API, universally, JSON Data format is accepted across all the platforms and languages. In every programming language, there is support for dealing with JSON Data. We often need to convert JSON to String or JSON to Object or vice versa in almost every programming language.

What is JSON

JSON Stands for Javascript Object Notation.

The JSON data-interchange format is accessible for humans to read and write, and efficient for machines to parse and generate.

JSON (JavaScript Object Notation) is the simple data interchange format. Syntactically it resembles the objects and arrays of JavaScript.

It is mostly used for communication between back-ends and JavaScript programs running in the browser, but it is used in other kind of applications as well.

It’s home page, json.org, provides a wonderfully bright and concise definition of the standard.

Let’s deep dive into the Golang JSON example.

Golang JSON

To work with JSON in Go, we first need to import the in-built package.

import "encoding/json"

Encoding JSON in Go

We can encode JSON data using the Marshal function.

func Marshal(v interface{}) ([]byte, error)

Let’s see the following complete code example.

// hello.go

package main

import (
	"encoding/json"
	"fmt"
	"log"
)

// Marshal function returns the JSON encoding of arguments
func Marshal(frozen2 interface{}) ([]byte, error) {
	return json.Marshal(frozen2)
}

// Frozen structure
type Frozen struct {
	Name   string
	Gender int32
	Movie  string
}

func main() {
	anna := Frozen{"Anna", 18, "Frozen 2"}

	elsa, err := json.Marshal(anna)
	if err != nil {
		log.Println(err)
	}
	fmt.Printf("%s\n", elsa)
}

Output

➜  hello go run hello.go
{"Name":"Anna","Gender":18,"Movie":"Frozen 2"}                                  
➜  hello

First of all, we have imported three packages.

  1. encoding/json
  2. fmt
  3. log

Then we have defined a function called Marshal. Let’s deep dive into Marshal function in Go.

func Marshal in Go

See the following syntax.

func Marshal(v interface{}) ([]byte, error)

Marshal returns the JSON encoding of v. The v is any valid data structure.

Marshal traverses the value v recursively.

If the encountered value implements the Marshaler interface and is not a nil pointer, Marshal calls its MarshalJSON method to produce the JSON.

If there is no MarshalJSON present, but the value implements the encoding.TextMarshaler, instead of an interface then, Marshal calls its MarshalText method and encodes the result as the JSON string.

The nil pointer exception is not strictly necessary but mimics the similar, appropriate exception in the behavior of UnmarshalJSON.

Otherwise, Marshal function uses the following type-dependent default encodings:

Boolean values encode as the JSON booleans.

Floating point, integer, and Number values encode as the JSON numbers.

String values encode as the JSON strings coerced to valid UTF-8, replacing invalid bytes with the Unicode replacement rune.

So that the JSON will be safe to embed inside HTML <script> tags, the string is encoded using HTMLEscape, which replaces “<“, “>”, “&”, U+2028, and U+2029 are escaped to “\u003c”,”\u003e”, “\u0026”, “\u2028”, and “\u2029”. This replacement can be disabled when using the Encoder, by calling SetEscapeHTML(false).

Array and slice values encode as the JSON arrays, except that []byte encode as a base64-encoded string, and a nil slice encodes as the null JSON value.

Struct values encode as JSON objects. Each exported struct field becomes the member of an object, using the field name as the object key unless the field is omitted for one of the reasons given below.

  1. The encoding of each struct field can be customized by the format string stored under the “json” key in the struct field’s tag.
  2. The format string gives the name of the field, possibly followed by a comma-separated list of options.
  3. The name may be empty to specify options without overriding the default field name.

The next step is that we have defined a struct.

Inside the main() function, we have created the structure called Anna and pass that object to the json.Marshal() function, and it will convert it to JSON.

To print the readable json data into the console, we are using a string package, and that is it.

We have successfully converted data from Struct to JSON.

Points to remember

Only data structures that can be represented as valid JSON will be encoded:

  1. JSON objects only support the strings as keys; to encode the Go map type, it must be of the form map[string]T (where T is any type supported by the json package).
  2. Channel, complex, and function types cannot be encoded in JSON.
  3. Cyclic data structures are not supported; they will cause Marshal function to go into the infinite loop.
  4. Pointers will be encoded as the values they point to (or ‘null’ if the pointer is nil).

Go 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.

func MarshalIndent in Go

MarshalIndent is like Marshal but applies Indent to format the output.

Each JSON item in the output will begin on a new line starting with a prefix followed by one or more copies of indent according to an indentation nesting.

See the following code.

// hello.go

package main

import (
	"encoding/json"
	"fmt"
	"log"
)

// Frozen structure
type Frozen struct {
	Name   string
	Gender int32
	Movie  string
}

func main() {
	anna := Frozen{"Anna", 18, "Frozen 2"}

	elsa, err := json.MarshalIndent(anna, "", "   ")
	if err != nil {
		log.Println(err)
	}
	fmt.Printf("%s\n", elsa)
}

In the above code, we have not created a separate Marshal function.

We call the json package’s MarshalIndent function and pass three parameters.

  1. Any valid data structure
  2. prefix
  3. indent

See the following output.

Output

➜  hello go run hello.go
{
   "Name": "Anna",
   "Gender": 18,
   "Movie": "Frozen 2"
}
➜  hello

func Unmarshal()

Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v.

If v is nil or not a pointer, Unmarshal returns the InvalidUnmarshalError.

Unmarshal uses the inverse of the encodings that Marshal uses, allocating the maps, slices, and pointers as necessary, with the following additional rules.

To unmarshal JSON into the pointer, Unmarshal first handles the case of the JSON being the JSON literal null. In that case, Unmarshal sets the pointer to nil.

Otherwise, Unmarshal unmarshals the JSON into the value pointed at by the pointer. If the pointer is nil, Unmarshal allocates the new value for it to point to.

To unmarshal JSON into the value implementing an Unmarshaler interface, the Unmarshal calls that value’s UnmarshalJSON method, including when input is a JSON null. Otherwise, if the value implements encoding, Textunmarshaler, and the input is a JSON quoted string, Unmarshal calls that value’s UnmarshalText method with the unquoted form of the string.

To unmarshal JSON into the struct, Unmarshal matches the incoming object keys to the keys used by the Marshal (either the struct field name or its tag), preferring the exact match but also accepting the case-insensitive match.  By default, object keys that don’t have the corresponding struct field are ignored (see Decoder.DisallowUnknownFields for an alternative).

To unmarshal the JSON into an interface value, Unmarshal stores one of these in the interface value:

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null

To unmarshal the JSON array into a slice, Unmarshal resets the slice length to zero and then appends each element to the slice. As a particular case, to unmarshal the empty JSON array into the slice, Unmarshal replaces the slice with a new empty slice.

To unmarshal the JSON array into the Go array, Unmarshal decodes JSON array items into corresponding Go array items. If the Go array is smaller than the JSON array, the additional JSON array items are discarded. If the JSON array is smaller than the Go array, the other Go array items are set to zero values.

To unmarshal the JSON object into a map, Unmarshal first establishes a map to use. If the map is nil, Unmarshal allocates a new map. Otherwise, Unmarshal reuses the existing map, keeping existing entries. Unmarshal then stores key-value pairs from the JSON object into the map. The map’s key type must either be a string, an integer or implement encoding.TextUnmarshaler.

If the JSON value is not appropriate for a given target type, or if the JSON number overflows the target type, Unmarshal skips that field and completes the unmarshaling as best it can. If no more serious errors are encountered, Unmarshal returns the UnmarshalTypeError describing the earliest such error. In any case, it’s not guaranteed that all the remaining fields following the problematic one will be unmarshaled into the target object.

The JSON null value unmarshals into an interface, map, pointer, or slice by setting that value to nil. Because null is often used in JSON to mean “not present,” unmarshaling a JSON null into any other Go type has no effect on the value and produces no error.

When unmarshaling quoted strings, invalid UTF-8 or invalid UTF-16 surrogate pairs are not treated as an error. Instead, they are replaced by the Unicode replacement character U+FFFD.

See the following code.

// hello.go

package main

import (
	"encoding/json"
	"fmt"
	"log"
)

// Frozen structure
type Frozen struct {
	Name   string
	Gender int32
	Movie  string
}

func main() {
	anna := Frozen{"Anna", 18, "Frozen 2"}
	fmt.Println("Simple Struct", anna)
	elsa, err := json.MarshalIndent(anna, "", "   ")
	if err != nil {
		log.Println(err)
	}
	fmt.Println("Marshal Struct to JSON")
	fmt.Printf("%s\n", elsa)

	err2 := json.Unmarshal(elsa, &anna)
	if err2 != nil {
		log.Println(err2)
	}
	fmt.Println("Unmarshal JSON to Struct")
	fmt.Printf("%+v", anna)
}

Output

➜  hello go run hello.go
Simple Struct {Anna 18 Frozen 2}
Marshal Struct to JSON
{
   "Name": "Anna",
   "Gender": 18,
   "Movie": "Frozen 2"
}
Unmarshal JSON to Struct
{Name:Anna Gender:18 Movie:Frozen 2}                                            
➜  hello

In the above code, we are using Marshal function to convert from struct to json and then Unmarshal function to convert from json to struct.

Conclusion

In this Golang JSON Example | How To Use JSON With Go article, we have seen the following topics.

  1. How to import and use the json package.
  2. How to use json.Marshal function.
  3. How to use json.MarshalIndent function.
  4. How to use json.UnMarshal function.

Finally, Golang JSON Example | How To Use JSON With Go tutorial is over.

Recommended Posts

Golang Log Example

Golang Template Example

Golang Slice Append Example

Golang Interface Example

Golang Custom Type Example

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.