How to parse huge json in Golang

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

How to parse huge json in Golang

问题

我是你的中文翻译助手,以下是翻译好的内容:

我是Go语言的新手,我正在尝试解析大型的JSON数据,比如从API获取的数据,其中包含大量的数据。文档解释了如何使用任何JSON来完成这个任务:

b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)
var f interface{}
err := json.Unmarshal(b, &f)
m := f.(map[string]interface{})

这段代码可以正常工作,但是当我使用从Twitter API获取的JSON数据时,比如在Twitter开发者网站的参考文档的末尾,我会遇到以下错误:

interface conversion: interface {} is []interface {}, not map[string]interface {}

我知道有类似的问题,但是我找不到答案。有人能推荐一种更好的解决方法吗?

我的Go版本是go1.6.2 linux/amd64。

谢谢!

英文:

I'm new to Golang and I am trying to parse large json like the ones you get from an API which have lots of data. The documentation explains how to do this with any json:

b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)
var f interface{}
err := json.Unmarshal(b, &f)
m := f.(map[string]interface{})

This works fine, but when I use a json that I get from the Twitter API, like the one at the end of the reference on the Twitter dev site I get this error:

> interface conversion: interface {} is []interface {}, not map[string]interface {}

I know that there are similar questions but I couldn't find the answer. Can someone recommend me the better way to solve this?

My go version go1.6.2 linux/amd64.

Thanks !

答案1

得分: 4

在这种情况下,你不是在解组一个单独的 JSON 对象,而是一个 JSON 对象数组,这就是为什么你在解析 API 响应时遇到问题的原因。你看到的错误是告诉你 f 的实际类型。另一个示例起作用是因为它是一个单独的 JSON 对象,可以映射为 map[string]interface{}。看一下这个例子:

var f []interface{}
err := json.Unmarshal(str, &f)
if err != nil {
    fmt.Println(err)
    return
}

for _, v := range f {
    z := v.(map[string]interface{})
    for k2, v2 := range z {
        fmt.Println("Key:", k2, "Value:", v2)
    }
}

f 应该是 []interface{} 类型的接口数组。根据你计划如何解析 API 响应,你可以像我在 for 循环中所做的那样,展示每个键值对。

英文:

In this case you are not unmarshalling a single JSON object, but an array of JSON objects which is why you're having an issue parsing the API response. The error your seeing this is telling you the actual type of f. The other example worked because it is a single JSON object, which can be mapped as a map[string]interface{} Take a look at this:

var f []interface{}
err := json.Unmarshal(str, &f)
if err != nil {
	fmt.Println(err)
	return
}

for _, v := range f {
	z := v.(map[string]interface{})
	for k2, v2 := range z {
		fmt.Println("Key:", k2, "Value:", v2)
	}
}

f should be of type []interface{} an array of interfaces. Depending on how you plan on parsing the API response, you can do something like I'm doing in the for loop to present each key, value pair.

huangapple
  • 本文由 发表于 2017年1月23日 09:27:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/41798046.html
匿名

发表评论

匿名网友

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

确定