unmarshal嵌套json,不知道结构

Bra*_*cil 8 go

我使用键值存储作为我的golang应用程序的后端,日期用作键(保持条目排序)和json文档作为值.的JSON的顶层名字空间(foo),并且typedate 都存在我存储但除此之外也有一些差异(特别是相对于一些嵌套JSON数据),每个JSON文档中,因此,当keyI'm从数据库中提取,我真的不知道我在循环中随时都会拔出什么东西.以下是json数据的示例

{ "foo": { "id":"124", "type":"baz", "rawdata":[123, 345,345],"epoch": "1433120656704"}}
{ "foo" : { "id":"234", "type":"bar", "rawdata":[{"key":"dog", "values":[123,234]}, {"key":"cat", "values":[23, 45]}], "epoch":"1433120656705"}}
Run Code Online (Sandbox Code Playgroud)

当我从数据库中取出时,我要做的第一件事就是将每个条目解组为一个map[string]*json.RawMessage来处理foo命名空间

//as I'm looping through the entries in the database
   var objmap map[string]*json.RawMessage
   if err := json.Unmarshal(dbvalue, &objmap); err !=nil{
       return err
   }
Run Code Online (Sandbox Code Playgroud)

我感谢这个答案

然而,与那个SO答案不同,当我必须再次解组foo命名空间中包含的内容时,我不知道将哪个结构解组为

   if err :=json.Unmarshal(*objmap["foo"], &bazorbar; err != nil{
         return err
   }

 type Baz struct{
  Id string `json:"id"`
  Type string `json:"type"`
  RawData []int `json:"rawdata"`
  Epoch string  `json:"epoch"`
}

type Bar struct{
  Id string `json:"id"`
  Type string `json:"type"`
  RawData []*Qux `json:"rawdata"`
  Epoch string  `json:"epoch"`
}
//nested inside Bar
type Qux struct{
  Key string `json:"key"`
  Values []int `json:"values`
}
Run Code Online (Sandbox Code Playgroud)

两部分问题:

  1. 有没有办法避免重复的解组(或者是我不应该关心的事情)
  2. 我怎样才能找出将json.RawMessage解组成哪个结构(这也允许嵌套的json数据)

更新: @chendesheng提供的初始答案使我能够找到类型,但一旦确定了该类型(我需要这样做),就不会再解组成结构,所以基于对他/她的评论中的对话回答,我会对这些可能性中的任何一种感兴趣

a)制作一个json.RawMessage的副本,在你显示的界面中解组(通过chendesheng的回答),然后一旦你知道了类型(从解组到接口),就解组了它的结构吗?

b)使用正则表达式确定类型,然后在知道该类型的结构后解组

che*_*eng 8

检查结构类型的两种方法:

  1. 将json.RawMessage解组为map [string] interface {}
  2. 使用正则表达式提取类型字符串

http://play.golang.org/p/gfP6P4SmaC