简体   繁体   English

将 JSON 解组为地图

[英]Unmarshal JSON into map

I have a really simple JSON file, something like this, but with thousands of strings:我有一个非常简单的 JSON 文件,类似这样,但有数千个字符串:

{"fruits":["apple","banana","cherry","date"]}

and I want to load the fruits into a我想把水果装进

map[string]interface{}

What is the best method?最好的方法是什么? Is there a way where I don't need to iterate over each element and insert into the map using a loop?有没有一种方法不需要遍历每个元素并使用循环插入地图?

here is example how you can Unmarshal to string list without any struct.这是您如何在没有任何结构的情况下解组到字符串列表的示例。

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
 }

Or instead of String list you can use map[string][]interface{}或者您可以使用map[string][]interface{}而不是 String 列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM