0

I need to keep numbers passed in the JSON that are fit the requirements to be an int32s to be stored in the database as int32 instead of a float.

I have a Go application that receives JSON request data that is inserted into a Mongo database. This data is unmarshalled into an interface and passed into mgo's Insert method (https://godoc.org/github.com/globalsign/mgo#Collection.Insert).

By default, to unmarshal data into an interface, Go converts numbers into float64s. The problem I am having is that integers unmarshalled from the JSON are not having their types preserved properly, all numbers are passed in as floats and after the insertion into Mongo, the data is saved as a float. Understandably, this is due to the restrictions on typing when using JSON as data holder.

Since the JSON data is not well-defined and may include different types of nested dynamic objects, creating structs for this problem doesn't appear to be a viable option.

I have researched some options that include iterating over the JSON data and using the UseNumbers() for decoding, but issue I am facing with this is that the operation could be expensive, as some of the JSON data may contain several hundreds of fields and reflection over those fields may cause slowdown while handling requests, although I am not aware of how impactful the performance hit would be.

2
  • 5
    If you don't know what the performance impact would be, don't worry about it. Just write what works, then measure to see if you actually have a performance problem, and profile to see where performance can be improved. Commented Apr 23, 2019 at 16:50
  • It's also worth noting that MongoDB uses Numbers for types (docs.mongodb.com/manual/reference/bson-type-comparison-order). I don't see how you could preserve type int after saving to Mongo anyway. edit: apparently you can cast it: stackoverflow.com/questions/8218484/… Commented Apr 23, 2019 at 21:19

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.