在golang中解析JSON的一个子段
我有一个接收JSON消息的应用程序。JSON有各种“部分”(下面的示例)。每个部分都有一个名称,但除此之外,每个部分的结构完全不同 我要做的是遍历各个部分,并为每个部分解组相应的对象。但奇怪的是,我发现这很困难,因为似乎您可以将整个JSON解组到一个对象中,或者您可以得到一个通用的map[string]接口{}。我找到的所有示例代码都涉及到类型切换和手动分配变量……我希望直接将neato解组处理到对象中 有没有办法将JSON的一个子集提供给解组器?我自己也可以对字节[]进行切分,但这似乎很可怕……其他人肯定也经历过类似的事情吗 这是我玩过的在golang中解析JSON的一个子段,json,go,Json,Go,我有一个接收JSON消息的应用程序。JSON有各种“部分”(下面的示例)。每个部分都有一个名称,但除此之外,每个部分的结构完全不同 我要做的是遍历各个部分,并为每个部分解组相应的对象。但奇怪的是,我发现这很困难,因为似乎您可以将整个JSON解组到一个对象中,或者您可以得到一个通用的map[string]接口{}。我找到的所有示例代码都涉及到类型切换和手动分配变量……我希望直接将neato解组处理到对象中 有没有办法将JSON的一个子集提供给解组器?我自己也可以对字节[]进行切分,但这似乎很可怕…
package main
import "encoding/json"
type Book struct {
Author string
Title string
Price float64
}
type Movie struct {
Title string
Year float64
Stars float64
Format string
}
var sections map[string]interface{}
func main() {
/*
* "Book" and "Movie" are "sections".
* There are dozens of possible section types,
* and which are present is not known ahead of time
*/
incoming_msg_string := `
{
"Book" : {
"Author" : "Jack Kerouac",
"Title" : "On the Road",
"Price" : 5.99
},
"Movie" : {
"Title" : "Sherlock Holmes vs. the Secret Weapon",
"Year" : 1940,
"Stars" : 2.5,
"Format" : "DVD"
}
}`
/*
* this code gets me a list of sections
*/
var f interface{}
err := json.Unmarshal([]byte(incoming_msg_string), &f)
if err != nil {
panic(err)
}
var list_of_sections []string
for section_type, _ := range f.(map[string]interface{}) {
list_of_sections = append(list_of_sections, section_type)
}
/*
* next I would like to take the JSON in the "book" section
* and unmarshal it into a Book object, then take the JSON
* in the "movie" section and unmarshal it into a Movie object,
* etc.
*
* https://blog.golang.org/json-and-go has an example on
* decoding arbitrary data, but there's only one Unmarshaling.
*
* json.RawMessage has an example in the docs but it assumes
* the objects are the same type (I think). My attempts to use
* it with a two-field struct (section name, and a raw message)
* gave runtime errors. Likewise unmarshaling into a
* []json.RawMessage gave "panic: json: cannot unmarshal object into Go value of type []json.RawMessage"
*
* What I'm looking for is something like:
* json.Unmarshal(some_json["a certain section"],&object)
*
*/
}
非常感谢任何面包屑线索提示。对
类型节映射[string]json.RawMessage
变量进行初始解组。然后,您将拥有与之关联的节类型和原始数据。您可以打开节类型并将其解组到特定的节结构,或者将其解组到映射[string]接口{}并以一般方式处理它们。(无论什么对你的应用程序最有效。)谢谢你——这太好了。我不知道为什么几个小时的谷歌搜索和实验并没有揭示出这种简单性,但这是一个学习的夜晚:-)谢谢。