Skip to content
zelenko edited this page Nov 18, 2020 · 7 revisions

How to create JSON object in Go:

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	data := make(map[string]interface{})
	data["name"] = "John Doe"
	data["title"] = "Golang Developer"
	data["phone"] = map[string]interface{}{
		"mobil":  "123-456-799",
		"office": "964-587-154",
	}
	data["email"] = "[email protected]"
	jsonData, err := json.Marshal(data)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	fmt.Println(string(jsonData))
}

The result is:

{
    "email": "[email protected]",
    "name": "John Doe",
    "phone": {
        "mobil": "123-456-799",
        "office": "964-587-154"
    },
    "title": "Golang Developer"
}

The same thing with formatting:

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	data := make(map[string]interface{})
	data["name"] = "John Doe"
	data["title"] = "Golang Developer"
	data["phone"] = map[string]interface{}{
		"mobil":  "123-456-799",
		"office": "964-587-154",
	}
	data["email"] = "[email protected]"

	fmt.Print(JSON(data))
}

func JSON(list interface{}) string {
	result, _ := json.MarshalIndent(list, "", "  ")
	return string(result)
}

Read multiple objets:

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
)

var j = []byte(`
{"a":1}
{"a":2}
{"a":3}
`)

func main() {
	dec := json.NewDecoder(bytes.NewBuffer(j))

	for {

		var v interface{}
		err := dec.Decode(&v)
		if err == io.EOF {
			break
		} else if err != nil {
			fmt.Println(err)
		}

		fmt.Println(v)
	}
}

Clone this wiki locally