在Golang中,有没有一种简单的方法可以解析任意复杂的JSON数据?

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

golang is there an easy way to unmarshal arbitrary complex json

问题

每个我在网上找到的例子都展示了如何构建用于存储数据的结构体,然后将JSON解组成该数据类型。问题是,我得到的是一大堆JSON数据,使用这种方法似乎非常费力...

有没有一种方法可以将大量的数据解组成类似于JSON/映射的对象,以便能够进行类似于JSON/映射的操作?

我现在的代码是这样的...

var data map[interface{}]interface{}
err = json.Unmarshal(JSONDUMP, &data)
if err != nil { log.Fatal(err) }

但是我不能像这样调用它

data["some"]["long"]["chain"]["of"]["lookups"]
(类型interface {}不支持索引操作)
英文:

Every example I come to online shows examples of building structs for the data and then unmarshaling JSON into the data type. The problem is that what I am getting is massive dump of JSON and it seems like backbreaking labor to use such a method....

Is there a way to take a huge dump of data and get it to unmarshal into a map like object that would function similar to json/maps?

What I have right now is like this...

var data map[interface{}]interface{}
err = json.Unmarshal(JSONDUMP, &data)
if err != nil { log.Fatal(err) }

but then I cannot call it like this

data["some"]["long"]["chain"]["of"]["lookups"] 
(type interface {} does not support indexing)

答案1

得分: 12

一般来说,这是一个不好的主意!但如果你真的需要,你可以这样做:

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	var anyJson map[string]interface{}

	customJSON := []byte(`{"a": "文本内容在这里", "b": {"c":10, "d": "更多文本"}}`)

	json.Unmarshal(customJSON, &anyJson)

	fmt.Println("a ==", anyJson["a"].(string))

	b_temp := anyJson["b"].(map[string]interface{})
	fmt.Println("c ==", b_temp["c"].(float64))
}

然后你可以像这样使用任何字段 anyJson["a"].(string) - 注意类型断言,它非常重要以确保有效。

英文:

In general this is a bad idea! But if you really need, you can do like this:

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	var anyJson map[string]interface{}

	customJSON := []byte(`{"a": "text comes here", "b": {"c":10, "d": "more text"}}`)

	json.Unmarshal(customJSON, &anyJson)

	fmt.Println("a ==", anyJson["a"].(string))

	b_temp := anyJson["b"].(map[string]interface{})
	fmt.Println("c ==", b_temp["c"].(float64))
}

.. then you can use any field like anyJson["a"].(string) - look at type assertion, it's critically important to be valid

答案2

得分: 11

你可以使用第三方库,例如gabsjason

data := []byte(`{
    "outter":{
        "inner":{
            "value1":"test"
        }
     }`)

Gabs:

jsonParsed, err := gabs.ParseJSON(data)
value, ok = jsonParsed.Path("outter.inner.value1").Data().(string)

Jason:

v, _ := jason.NewObjectFromBytes(data)
value, _ := v.GetString("outter","inner","value1")
英文:

You can use third party libraries such as gabs or jason.

data := []byte(`{
    "outter":{
        "inner":{
            "value1":"test"
        }
     }`)

Gabs :

jsonParsed, err := gabs.ParseJSON(data)
value, ok = jsonParsed.Path("outter.inner.value1").Data().(string)

Jason :

v, _ := jason.NewObjectFromBytes(data)
value, _ := v.GetString("outter","inner","value1")

huangapple
  • 本文由 发表于 2017年2月10日 14:20:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/42152750.html
匿名

发表评论

匿名网友

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

确定