Efficiently Unmarshal JSON into a Map
In the realm of programming, parsing data from external sources plays a crucial role. When dealing with JSON, a ubiquitous data format, the ability to efficiently unmarshal it into a map becomes essential.
Suppose you encounter the following JSON data:
{"fruits":["apple","banana","cherry","date"]}
and aim to load the "fruits" into a map[string]interface{}. The conventional approach involves iterating through each element and inserting it into a map via a loop. However, a more efficient method exists that eliminates the need for loop iteration.
Direct Unmarshal without Iteration
To unmarshal the JSON data directly into the desired map without manual loop iteration, follow these steps:
Example Implementation
package main
import "fmt"
import "encoding/json"
func main() {
src_json := []byte(`{"fruits":["apple","banana","cherry","date"]}`)
var m map[string][]string
err := json.Unmarshal(src_json, &m)
if err != nil {
panic(err)
}
fmt.Printf("%v", m["fruits"][0]) //apple
}
Note: This approach assumes that the JSON values are all strings. If the values are of a different type, you may need to modify the map type accordingly (e.g., map[string][]interface{}).
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3