Skip to content

Instantly share code, notes, and snippets.

@arshamalh
Created March 5, 2022 00:13
Show Gist options
  • Save arshamalh/e8344306e355660a99be21e2f36d19b6 to your computer and use it in GitHub Desktop.
Save arshamalh/e8344306e355660a99be21e2f36d19b6 to your computer and use it in GitHub Desktop.
Reading and writing JSON objects in Golang
package main
import (
"encoding/json"
"fmt"
)
func main() {
myJson := map[string]interface{}{
"name": "Arsham",
"age": 22,
"male": true,
}
myJsonBytes, err := json.Marshal(myJson)
if err != nil {
fmt.Print(err)
}
fmt.Println(string(myJsonBytes))
}
package main
import (
"encoding/json"
"fmt"
)
type myJsonStructure struct {
Name string `json:"name_customized_field"` // You can customize your fields names like this.
Age int `json:"age"`
Male bool `json:"male"`
}
func main() {
myJson := &myJsonStructure{"Arsham", 22, true}
myJsonBytes, err := json.Marshal(myJson)
if err != nil {
fmt.Print(err)
}
fmt.Println(string(myJsonBytes))
}
// This is for times we know what we will get, actually what keys we have in our JSON.
// This is a full example including type convertions and Get request and error handeling.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
)
type ResponseJSON struct {
UserID int `json:"userId"`
ID int `json:"id"`
Title string `json:"title"`
Completed bool // If the only difference is first capital C, we don't need to write `json:"completed"`
}
func main() {
resp, err := http.Get("https://jsonplaceholder.typicode.com/todos/1")
if err != nil {
fmt.Print(err)
}
responseByteValue, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Print(err)
}
defer resp.Body.Close()
response := &ResponseJSON{}
json.Unmarshal(responseByteValue, response)
fmt.Printf("%s - %s - %s", response.Title, strconv.FormatBool(response.Completed), strconv.Itoa(response.UserID))
}
// This example is for times we don't know what keys we will have in our json
// Actually when json structure is kind of unknown for us
// I removed error handelings to increase simplicity, but you know where to place them.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
resp, _ := http.Get("https://jsonplaceholder.typicode.com/todos/1")
responseByteValue, _ := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
var response map[string]interface{}
json.Unmarshal([]byte(responseByteValue), &response)
fmt.Printf("%+v\n", response)
fmt.Printf("%+v\n", response["title"])
}
// This code won't run alone, it is just a snippet for copy/paste! or even seeing steps clearly.
import (
"encoding/json"
"io/ioutil"
)
type ResponseJSON struct {}
// data variable is something that implements reader interface
byteValue := ioutil.ReadAll(data)
response := &ResponseJSON{}
json.Unmarshal(responseByteValue, response)
fmt.Printf("%+v\n", response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment