How to encode map data into a JSON string in Go by example?
Encode map data into a JSON string in Go
In Go, encoding map data into a JSON string involves using the
encoding/json
package, which provides a set of functions for encoding and decoding JSON data.
Example
package main
import (
"encoding/json"
"fmt"
)
func main() {
// create a map containing some data
data := map[string]interface{}{
"name": "John Doe",
"age": 30,
"address": map[string]string{
"city": "New York",
"state": "NY",
},
}
// encode the map data into a JSON string
jsonData, err := json.Marshal(data)
if err != nil {
fmt.Println("Error encoding JSON:", err)
return
}
// print the encoded JSON string
fmt.Println(string(jsonData))
}
Output
{"address":{"city":"New York","state":"NY"},"age":30,"name":"John Doe"}
Explaination
we create a map called data
containing some data. The map has three keys (name
, age
, and address
), and the address
key contains another map with two keys (city
and state
).
To encode the map data into a JSON
string, we use the json.Marshal()
function. The argument to json.Marshal()
is the map we want to encode, and the function returns a byte slice containing the encoded JSON data.
If there is an error encoding the JSON data, json.Marshal()
returns an error, which we handle by printing an error message and returning from the main()
function.
Finally, we print out the encoded JSON string to the console using fmt.Println()
.
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go