Home  >  Article  >  Backend Development  >  How to Unmarshal JSON into a Go Map without Loops?

How to Unmarshal JSON into a Go Map without Loops?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 21:33:02195browse

 How to Unmarshal JSON into a Go Map without Loops?

Unmarshal JSON into Map

This question addresses the challenge of loading JSON data into a Go map. Specifically, a simple JSON file containing an array of strings is provided, and the goal is to unmarshal the fruits list into a map with string keys and interface{} values. The question also inquires if there is an efficient way to avoid using loops for inserting elements into the map.

To answer this question, we can take advantage of Go's powerful encoding/json package. By unmarshaling the JSON data directly to a map[string][]string, we can bypass the need for iteration and manual insertion:

<code class="go">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
}</code>

This code efficiently converts the JSON into a map where the key "fruits" maps to a list of strings. It avoids loops and manual insertion, making it both concise and performant. Alternatively, you can also use map[string][]interface{} as the target type if you prefer to keep the values as generic interfaces.

The above is the detailed content of How to Unmarshal JSON into a Go Map without Loops?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn