英文:
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
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论