What is JSON used for?

You can encode values to json. You can use JSON to communicate between different programs. They dont necessarily need to be both Go (golang) programs. Lets name them program A and program B.

A message object can be encoded to JSON:

1
{ message: "Hello" }

JSON is structured data values. Program A creates an JSON message.

The other program, program B, then can decode the JSON message and convert it to a data structure inside program B.

Note
In Go different terminology is used than other programming languages
Encoding is called Marshall and decoding is called Unmarshal

Related course: Introducing Go: Build Reliable, Scalable Programs

Why JSON?

There are a few reasons to use JSON

  • Human readable
  • Computer readable
  • Widely used

Example

You can encode anything to JSON. First you need to load the required packages.

In the example below the fmt package is used for output and the package encoding/json is used for json encoding.

Then we define a struct for the JSON output:

1
2
3
4
type user struct {
Username string
Password string
}

The first letter of every field must be in uppercase.

In this example a list is converted, the list is defined like this:

1
2
3
4
5
users := []user{
{"debora","123456"},
{"bob","42"},
{"sandra","33"},
}

Then the list is converted to a json string using the Marshal() function. The complete example is shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main

import "encoding/json"
import "fmt"

type user struct {
Username string
Password string
}

func main() {
users := []user{
{"debora","123456"},
{"bob","42"},
{"sandra","33"},
}

// use marshal func to convert to json
out, err := json.Marshal(users)
if err != nil {
fmt.Println(err)
return
}

// print encoded json data
fmt.Println(string(out))
}

This outputs JSON data this way:

1
[{"Username":"debora","Password":"123456"},{"Username":"bob","Password":"42"},{"Username":"sandra","Password":"33"}]

JSON formatting

If you want to use pretty formatting instead, you can use the function MarshalIdent(). I recommend using it like this:

1
out, err := json.MarshalIndent(users, "", "\t")

You then get a nicely formatted json string:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[
{
"Username": "debora",
"Password": "123456"
},
{
"Username": "bob",
"Password": "42"
},
{
"Username": "sandra",
"Password": "33"
}
]