Golang : How to convert JSON string to map and slice
Couple of simple examples on how to convert JSON string to map and slice(array).
Simple and straightforward way of converting one line of JSON string.
package main
import (
"encoding/json"
"fmt"
)
func main() {
jsonStr := `{"Name":"Adam","Age":36,"Job":"CEO"}`
personMap := make(map[string]interface{})
err := json.Unmarshal([]byte(jsonStr), &personMap)
if err != nil {
panic(err)
}
for key, value := range personMap {
fmt.Println("index : ", key, " value : ", value)
}
}
Output:
index : Name value : Adam
index : Age value : 36
index : Job value : CEO
Convert multiple lines of JSON string to map and append each line into a slice(array).
package main
import (
"encoding/json"
"fmt"
"strconv"
)
func main() {
jsonStr := `[{
"Name": "Adam",
"Age": 36,
"Job": "CEO"
}, {
"Name": "Eve",
"Age": 34,
"Job": "CFO"
}, {
"Name": "Mike",
"Age": 38,
"Job": "COO"
}]`
type Person struct {
Name string
Age int
Job string
}
var people []Person
var personMap []map[string]interface{}
err := json.Unmarshal([]byte(jsonStr), &personMap)
if err != nil {
panic(err)
}
for _, personData := range personMap {
// convert map to array of Person struct
var p Person
p.Name = fmt.Sprintf("%s", personData["Name"])
p.Age, _ = strconv.Atoi(fmt.Sprintf("%v", personData["Age"]))
p.Job = fmt.Sprintf("%s", personData["Job"])
people = append(people, p)
}
fmt.Println(people)
}
Output:
[{Adam 36 CEO} {Eve 34 CFO} {Mike 38 COO}]
References:
https://www.socketloop.com/tutorials/golang-iterate-map
https://www.socketloop.com/references/golang-encoding-json-decoder-decode-function-example
https://www.socketloop.com/tutorials/golang-covert-map-slice-array-to-json-xml-format
See also : Golang : Covert map/slice/array to JSON or XML format
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+8.8k Golang : Serving HTTP and Websocket from different ports in a program example
+4.9k Golang : Convert lines of string into list for delete and insert operation
+31.9k Golang : Convert []string to []byte examples
+17.5k Golang : Qt image viewer example
+10.6k Golang : How to transmit update file to client by HTTP request example
+5.5k Javascript : How to replace HTML inside <div>?
+6.9k Golang : Dealing with postal or zip code example
+7.6k Swift : Convert (cast) String to Double
+13.7k Golang : Compress and decompress file with compress/flate example
+11.1k Golang : Delay or limit HTTP requests example
+15.3k Golang : Get checkbox or extract multipart form data value example
+34.2k Golang : Smarter Error Handling with strings.Contains()