Golang将JSON数组解析为数据结构

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

Golang parse JSON array into data structure

问题

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

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

由于这是一个具有动态键的JSON数组,我认为我可以使用:

type data map[string]string

然而,我无法使用map解析文件:

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

在Go中,将包含JSON数据的文件解析为数组(只有字符串到字符串类型)的最简单方法是什么?

编辑: 进一步说明接受的答案--我的JSON实际上是一个包含映射的数组。为了使我的代码工作,文件应该包含:

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

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

英文:

I am trying to parse a file which contains JSON data:

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

Since this is a JSON array with dynamic keys, I thought I could use:

type data map[string]string

However, I cannot parse the file using a map:

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

What would be the most simple way to parse a file containing a JSON data is an array (only string to string types) into a Go struct?

EDIT: To further elaborate on the accepted answer -- it's true that my JSON is an array of maps. To make my code work, the file should contain:

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

Then it can be read into a map[string]string

答案1

得分: 24

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

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)
}
英文:

Try this: http://play.golang.org/p/8nkpAbRzAD

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)
}

答案2

得分: 17

这是因为你的 JSON 实际上是一个映射数组,但你试图将其反序列化为一个普通的 map。尝试使用以下方式:

type YourJson struct {
    YourSample []struct {
        data map[string]string
    } 
}
英文:

It's because your json is actually an array of maps, but you're trying to unmarshall into just a map. Try using the following:

type YourJson struct {
	YourSample []struct {
		data map[string]string
	} 
}

答案3

得分: 4

你可以尝试使用bitly的simplejson包,它更加简单易用。你可以在https://github.com/bitly/go-simplejson找到它。

英文:

you can try the bitly's simplejson package
https://github.com/bitly/go-simplejson

it's much easier.

huangapple
  • 本文由 发表于 2014年8月24日 03:20:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/25465566.html
匿名

发表评论

匿名网友

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

确定