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:

{ 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

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:

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:

    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:

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:

[{"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:

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

You then get a nicely formatted json string:

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