Created
February 11, 2021 03:14
-
-
Save Miqueas/23fbb8d942fe8305f86b76f95d32eb4f to your computer and use it in GitHub Desktop.
[Go] Decode and encode JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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