Json data

(3 minutes for reading)

What is Json data?

“Json” is only a string which has structure, has grammar. And structure of json help it can contain data.

Example 1: a simple json data

"
{
    "name": "thaibao",
    "age": 32
}
"

Example 2: an array json data

"
[
  {
    "name": "thaibao",
    "age": 32
  }, {
    "name": "jerry",
    "age": 5
  }
]
"

Example 3: structure in structure data in json data

"
[
  {
    "name": "thaibao",
    "age": 32,
    "address" : {
      "street": "pasteur",
      "district": "district 1"
    }
  }, {
    "name": "jerry",
    "age": 5,
    "address": null,
  }
]
"

How to work on Json

1/ Using a struct to map data in json

We try to use this json data

jsonSimple := "
{
    "name": "thaibao",
    "age": 32
}
"

Declare a struct to map with data of json

type person struct {
    NameData string `json:"name"`
    AgeDate integer `json:"age"`
}

Use json build-in lib of Golang, we can parse string json in to a varialbe person type. Because Unmarshal function of json only get param json string in byte, so, we need to parse string json to []byte array. After make unmarshal, p get data from json string data

import "encoding/json"

function main() {
    p := person{}
    _ := json.Unmarshal([]byte(jsonSimple), &p)
    fmt.Println("person:", p)
}

2/ Using map interface with json data string

We can declare a map[string] interface to get data from json string data

function main() {
    personData := make(map[string] interface{})
    _ := json.Unmarshal([]byte(jsonSimple), &personData)
    fmt.Println("person:", personData)
}

With map, interface, struct, slice we have a lot of ways to get data from json string. If you don’t know, contact me to get them. Json data is very strong, and this is the best general method which almost website use to transfer data between server and client

Convert from Golang data to json string

Too easy, try to use and you should get a json string in byte array

jsonInBytes := json.Marshal(data)
// or
json.MarshalIndent(data, "", " 
   ")

fmt.Println("json data string", string(jsonInBytes))

View on github

PreNext