Float vs int ambiguity for json decoding

439 views
Skip to first unread message

Alex Flint

unread,
Oct 20, 2015, 5:25:49 PM10/20/15
to golang-nuts
I recently wrote a json pretty-printer for sequences of json objects in Golang. The file contains a sequence of json objects (not a json list) that look like:

    {"foo":bar"}{"ham":"spam"}...

The goal was to load sequences of arbitrary json objects and pretty-print them using json.MarshalIndent. So I Decode()d the data into an interface{} variable and then MarshalIndent'ed it. This worked fine except that all the numbers are now floats, so upon re-encoding some numbers that started out like "123123123" ended looking like "1.23123123e+08".

I then discovered json.Indent, which could deal with this case if I just had a single json object, but afaict it cannot deal with a sequence of json objects (and I do not know where the end points of each json object are - I was relying on Decode() to determine this for me). For example, this:

      var buf bytes.Buffer
err := json.Indent(&buf, []byte(`{"foo":"bar"}{"ham":"spam"}`), "", "  ")

gives an error, which is understandable since the string is not a valid json object.

Any suggestions on how to achieve this?

Nodir Turakulov

unread,
Oct 20, 2015, 5:55:45 PM10/20/15
to Alex Flint, golang-nuts
Call Decoder.UseNumber() prior decoding, it will prevent that

--
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...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

alex.flint

unread,
Oct 20, 2015, 8:21:27 PM10/20/15
to Nodir Turakulov, golang-nuts
Oh, wonderful!

Jason E. Aten

unread,
Oct 21, 2015, 4:18:16 PM10/21/15
to golang-nuts
Reply all
Reply to author
Forward
0 new messages