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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25465566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:30:08  来源:igfitidea点击:

Golang parse JSON array into data structure

jsonparsinggo

提问by Kiril

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

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

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

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

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

type data map[string]string

However, I cannot parse the file using a map:

但是,我无法使用以下命令解析文件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?

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

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:

编辑:为了进一步详细说明已接受的答案 - 我的 JSON 确实是一组地图。为了使我的代码工作,该文件应包含:

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

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

然后它可以被读入一个 map[string]string

采纳答案by Steve P.

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:

这是因为您的 json 实际上是一个地图数组,但您正试图将其解组为一个map. 尝试使用以下方法:

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

回答by Marko Kevac

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

试试这个: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)
}

回答by JessonChan

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

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

it's much easier.

这要容易得多。