将JSON解组到地图中 [英] Unmarshal JSON into map

查看:115
本文介绍了将JSON解组到地图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的JSON文件,类似这样,但是有成千上万个字符串:

I have a really simple JSON file, something like this, but with thousands of strings:

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

我想将水果装入一个

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
 }

或者您可以使用代替字符串列表 map[string][]interface{}

Or instead of String list you can use map[string][]interface{}

这篇关于将JSON解组到地图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆