Truncating Rails bigint with as_json

When models have bigint columns with values such as 1456299399553483799, they often get converted to slightly different numbers like 1456299399553483800 when using the as_json method.

Is there a simple or predefined method to automatically convert these big integers to strings during serialization in order to prevent truncation?

Answer №1

Here's a potential solution - I made an addition to the following code snippet as an initializer:

# config/initializers/bigint_serializer.rb

class Integer
  def as_json(options = nil)
    self > 2147483647 ? self.to_s : self
  end
end

This modification alters the default functionality of Numeric#as_json found at https://github.com/rails/rails/blob/v5.1.4/activesupport/lib/active_support/core_ext/object/json.rb#L95, converting numbers larger than a 4-byte signed max int into strings.

It's worth noting that you could potentially use a larger integer value before resorting to string conversion - possibly up to 9007199254740991. However, I kept it as a maximum 4-byte int since I didn't require smaller integers to be stored as strings (referenced in What is JavaScript's highest integer value that a Number can go to without losing precision?)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining JSON data in a separate JavaScript file using PHP

I have an HTML file with the following content: // target.html <html xmlns="http://www.w3.org/1999/xhtml"> ... <script src="../../Common/js/jquery-ui-1.10.3.js"></script> <script src="../../Common/js/select.js" type="text/javascript"& ...

Missing ) in the parenthetical section of ExtJs JSON in Zend Framework was not found

I'm currently facing a mysterious ghost error that indicates a missing closing parenthesis in a parenthetical. Despite reviewing similar questions and answers related to JSON issues, I can't seem to locate any faults in my code. Here's an ex ...

Trouble parsing JSON in Classic ASP

After receiving a JSON Response from a remote server, everything looks good. I discovered an helpful script for parsing the JSON data and extracting the necessary values. When attempting to pass the variable into JSON.parse(), I encountered an error which ...

Dealing with 404 errors in Apache mod_wsgi Flask when handling large json files

I have a Flask application set up with mod_wsgi on Apache. Within the app, I have a series of charts that retrieve data (~2Mb per file) from a static route @app.route('/data/<experiment_id>/<sensors>.json, where I utilize the JSON mimetype ...

Using Javascript to read a JSON string displayed in a URL

I'm working on developing a straightforward web application that extracts latitude and longitude data stored in a JSON format and places markers on a Google map based on this information. Currently, there is a program running on a server that generate ...

Filtering by two nested arrays with JsonPath

I have a JSON Document that needs to extract all emailAddresses associated with an 'email'-Contact from a specific source. The JSON data is as follows: { "errors": [ ], "individuals": [ { "contacts": ...

Checking the root object in a JSON list using Spring MVC

Looking for a solution to validate a JSON list with the following structure: [{"op":"A","path":"C","value":"B"},...] within a Spring MVC application. Currently, I am deserializing it to an object using default Jackson as shown below: public class Operat ...

Discover the process of extracting information from an array within a JSON file using a query in Microsoft Azure

What's the best way to retrieve the value of an element from an array in one of my inputs that constantly changes its index? I believe my query structure is correct. I have two inputs, and through a join operation, I'm successfully fetching data ...

Is it possible to utilize a JavaScript variable as a node in a JSON stringification request?

After successfully retrieving data from the Bungie API previously, I am now facing a challenge in reading a specific JSON file. http://prntscr.com/k3tin3 I'm currently stuck on how to extract a node from the JSON and then utilize it to request charac ...

Exploring the world of data transfer with Websockets in Flutter

What is the best way to convert JSON data into websocket data in a Flutter application? StreamBuilder( stream: _channel.stream, builder: (context, snapshot) { return ListView.builder( ...

Converting JSON data into GeoJSON format using JavaScript

Currently, I am in the process of reading a JSON file and formatting it for GeoJSON function getAddress(id,search,vagas, next) { geo.geocode({address:search}, function (results,status) { if (status == google.maps.GeocoderStatus.OK) { ...

Here are the steps to divide an array of objects into separate objects based on their keys

The data I currently have is formatted like this: [{ "Consumer": [{ "Associated ID": "JSUDB2LXXX / BIC 7503 / US", "Parent Consumer": "7503" }], "Owner": [{ &qu ...

Return a JSON array from a nested map operation

What is the best method for creating a nested JSON array? Are there any alternative approaches to achieve this? I attempted the following code: var m1 = make(map[string]interface{}) m1 = append(tickets, ptotal) //error is here i.Data ...

Pass a JSON object to PHP when AJAX call is successful

Within my Controller, there exists an array named $data. Here is the output of its var dump: array 'urls' => array 0 => array 'link_id' => string '1' (length=1) 'link_name ...

Obtain Python script output displayed in HTML format

I am currently working on developing Python scripts that can be utilized by front-end HTML+CSS developers for websites. To test the feasibility of this approach, I have written a basic script that makes use of parse.com as the backend. The script retrieves ...

Validating JSON Schema with date fields

I'm running into some challenges while using the JSchemaValidatingReader within the Newtonsoft.Json.Schema library. The problem arises when trying to validate date fields in JSON data. Here is an example of the schema and data being used: var schema ...

Having difficulty retrieving a JSON Object value through an angular2 pipe

I am currently working on creating a dynamic table using Angular2. I have set up an Angular2 component with two pipes: the first pipe successfully retrieves the key from the JSON object, which is used as the column for the table. However, the second pipe, ...

Unpacking JSON and extracting a value in C#

// Extracting the JSON response. string content = await response.Content.ReadAsStringAsync(); Console.WriteLine(content); var rsJson = Newtonsoft.Json.Linq.JToken.Parse(content); Result result = ...

Tips for configuring ejs data within the data attribute and processing it using client-side JavaScript

My aim is to transfer leaderboard information from the server to the client-side JavaScript. This is the code on my server side: const leaderboard = [[dog,cat],[car,bus],[foo,bar]] const toJson = JSON.stringify(leaderboard) res.render('gam ...

What is the method for sending a POST request with a JSON file containing a map using Postman?

I've been attempting to send a JSON containing a map in a POST request using Postman, but despite trying various combinations, I have had no success. For the Content-Type, I have set it to application/json. I came across this question: Sending map in ...