Unmarshal nested json without structure knowledge

I use a key value store as a backend for my golang application, and the date serves as a key (for sorting records) and json documents as values. Top-level namespace of the json ( foo) and typeand dateis present in every json-paper, which I have kept, but otherwise there are some differences (especially in respect of certain sub-json-data), so when keyI'm pulls from the database, I really do not know what I pull out anytime when I get hung up. Here is a sample json data

{ "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"}}

when I exit the database, the first thing I do is to not arm each entry in map[string]*json.RawMessagefor namespace processingfoo

//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
   }

which I do thanks to this SO answer

However, unlike this SO answer, when I have to turn off everything in the namespace again foo, I don’t know which structure should be undone in

   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`
}

Two parts Question:

  • Is there a way to avoid repeated riots (or is this something that I should not care about)
  • how can I determine which structure should json.RawMessage cancel (which also allows nested json data)

Update: the original answer provided by @chendesheng allows me to find out the type, but not to cancel the attempt again to the structure after this type has been defined (what I need to do), so in the conversation in the comments to his / her answer, I will be be interested in any of these possibilities.

a) json.RawMessage, , ( chendesheng answer), itno struct , (- )?

b) , , ,

+7
2

:

  1. Unmarshal json.RawMessage [] {}

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

+8

All Articles