我正在尝试解析一个包含JSON数据的文件:

1
2
3
4
5
[
  {"a" :"1"},
  {"b" :"2"},
  {"c" :"3"}
]

由于这是带有动态键的JSON数组,因此我认为我可以使用:

1
type data map[string]string

但是,我无法使用map解析文件:

1
2
3
4
5
6
7
c, _ := ioutil.ReadFile("c")
dec := json.NewDecoder(bytes.NewReader(c))
var d data
dec.Decode(&d)


json: cannot unmarshal array into Go value of type main.data

将包含JSON数据的文件解析为Go结构的最简单方法是将数组(仅字符串类型转换为字符串类型)?

1
2
3
4
5
{
 "a":"1",
 "b":"2",
 "c":"3"
}

然后可以将其读入map[string]string


试试这个:http://play.golang.org/p/8nkpAbRzAD

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

import (
   "encoding/json"
   "fmt"
   "io/ioutil"
   "log"
)

type mytype []map[string]string

func main() {
    var data mytype
    file, err := ioutil.ReadFile("test.json")
    if err != nil {
        log.Fatal(err)
    }
    err = json.Unmarshal(file, &data)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(data)
}
  • type mytype []map[string]string是否应为mytype map[string]string类型?

这是因为您的json实际上是一个地图数组,但是您试图将其编组为map。 尝试使用以下内容:

1
2
3
4
5
type YourJson struct {
    YourSample []struct {
        data map[string]string
    }
}
  • 是的,你是对的! 当文件格式与我的问题相同时,此方法有效。 我编辑了问题,以显示使它与map[string]string一起工作的另一种可能性。
  • 我们可以拥有完整的工作代码吗? 我尝试了以上YourJson结构,但没有成功。
  • 使用stackoverflow.com/a/25466050/248616的type YourJson []map[string]string可以为我工作

你可以尝试一下bitly的simplejson包
https://github.com/bitly/go-simplejson

这要容易得多。