英文:
Unmarshal JSON into map
问题
我有一个非常简单的JSON文件,类似于这样,但有成千上万个字符串:
{"fruits":["apple","banana","cherry","date"]}
我想将水果加载到一个
map[string]interface{}
中。最好的方法是什么?有没有一种方法可以不需要遍历每个元素并使用循环将其插入到地图中?
英文:
I have a really simple JSON file, something like this, but with thousands of strings:
{"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?
答案1
得分: 10
这是一个示例,演示如何在没有任何结构的情况下将数据解组为字符串列表。
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{}
代替字符串列表。
英文:
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{}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论