将JSON解析为map。

huangapple go评论103阅读模式
英文:

Unmarshal JSON into map

问题

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

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

我想将水果加载到一个

  1. map[string]interface{}

中。最好的方法是什么?有没有一种方法可以不需要遍历每个元素并使用循环将其插入到地图中?

英文:

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

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

and I want to load the fruits into a

  1. 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

这是一个示例,演示如何在没有任何结构的情况下将数据解组为字符串列表。

  1. package main
  2. import "fmt"
  3. import "encoding/json"
  4. func main() {
  5. src_json := []byte(`{"fruits":["apple","banana","cherry","date"]}`)
  6. var m map[string][]string
  7. err := json.Unmarshal(src_json, &m)
  8. if err != nil {
  9. panic(err)
  10. }
  11. fmt.Printf("%v", m["fruits"][0]) //apple
  12. }

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

英文:

here is example how you can Unmarshal to string list without any struct.

  1. package main
  2. import "fmt"
  3. import "encoding/json"
  4. func main() {
  5. src_json := []byte(`{"fruits":["apple","banana","cherry","date"]}`)
  6. var m map[string][]string
  7. err := json.Unmarshal(src_json, &m)
  8. if err != nil {
  9. panic(err)
  10. }
  11. fmt.Printf("%v", m["fruits"][0]) //apple
  12. }

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

huangapple
  • 本文由 发表于 2017年7月14日 17:56:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/45100021.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定