https://play.golang.org/p/gWQuthS0D6

On Wed, Dec 28, 2016 at 11:55 PM Sathish VJ <sathis...@gmail.com> wrote:

> aah, got it. the case []interface{}:  is what I'd not gotten right.
> Thanks for the detailed examples.
>
>
> On Thursday, 29 December 2016 12:57:54 UTC+5:30, Konstantin Khomoutov
> wrote:
>
> On Wed, 28 Dec 2016 21:55:33 -0800 (PST)
>
> Sathish VJ <sath...@gmail.com> wrote:
>
> > I'm trying to do custom json unmarshaling when there could be an
> > error.
> >
> > In case there is an error, it will have json like: { "error": "err
> > msg"} Else, it could be anything.
> >
> > If it is another json object, then I'm having no issues.  But if the
> > incoming data is an array, then it fails.  How do I take care of this
> > case?
> >
> > source: https://play.golang.org/p/xyiDWZh9Rt
>
> One way around this is to rely on Go's encoding/json doing the Right
> Thing™ when unmarshaling into a value of type interface{}.
> This way, you'll get an appropriately-typed value as a result, and
> could do type switching on it [1].
>
> The downside of this approach is that if your "non-error case" JSON
> streams are compilcated, and you'd like to actually parse them into
> objects of your custom (struct) types, this approach would require
> re-parsing the source JSON stream for a non-error case.
> You can get around this problem by resorting to low-level parsing of
> the JSON stream and switching the processing logic as soon as you
> detect you were sent a JSON object (which might contain the
> field "error" signalizing an error).  Unfortunately, the JSON decoder
> seems to not support "peeking" at the next token or "pushing back" the
> just read token so you'll need to resort to a somewhat contrived
> solution such as [2], which I'd use only if your "non-error case" data
> streams are large enough to warrant such dancing.
>
> You could also condider exploring 3rd-party JSON decoders such as [3] or
> [4] which might contain enough controls to facilitate such fine-grained
> parsing you need.
>
> 1. https://play.golang.org/p/VVm6pxN8rh
> 2. https://play.golang.org/p/6wntcKxKBR
> 3. https://github.com/ugorji/go
> 4. https://github.com/clbanning/mxj
>
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to