Skip to content

Instantly share code, notes, and snippets.

@Miqueas
Created February 11, 2021 03:14
Show Gist options
  • Save Miqueas/23fbb8d942fe8305f86b76f95d32eb4f to your computer and use it in GitHub Desktop.
Save Miqueas/23fbb8d942fe8305f86b76f95d32eb4f to your computer and use it in GitHub Desktop.
[Go] Decode and encode JSON
package main
import (
Fmt "fmt"
Str "strings"
Bytes "bytes"
JSON "encoding/json"
)
// Our JSON string to decode
const JSONStr = `{ "Name": "Jhon Doe", "Age": 35 }`
func main() {
// Our object where to store the decoded JSON
var obj map[string]interface{}
// Our buffer where to store the encoded JSON
var buf Bytes.Buffer
// The io.Reader needed by the JSON decoder
var read = Str.NewReader(JSONStr)
// Creates the decoder
var dec = JSON.NewDecoder(read)
// Creates the encoder
var enc = JSON.NewEncoder(&buf)
// Decodes the JSON
err := dec.Decode(&obj)
if err != nil { panic(err) }
Fmt.Printf("Decoded JSON (%T): %v\n", obj, obj)
// We just set some keys
obj["Company"] = "Some Company, Inc."
obj["Github"] = "https://github.com/JhonDoe"
obj["Repos"] = []string {
"https://github.com/JhonDoe/AwesomeRepo1",
"https://github.com/JhonDoe/AwesomeRepo2",
"https://github.com/JhonDoe/AwesomeRepo3",
}
// Encodes the new modified JSON
err = enc.Encode(&obj)
if err != nil { panic(err) }
// An the result is:
Fmt.Printf("Encoded JSON (%T): %v\n", obj, obj)
// If you want an string output, just cast ;)
Fmt.Printf("Encoded JSON (%T): %v\n", buf.Bytes(), buf.Bytes())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment