What is the proper way to convert nil to JSON as nil, without representing it as an empty value?

I'm facing an issue in my controller/action where some values turn out to be nil:

def my_action
  @var1 = get_boolean_value || nil
  @var2 = get_int_value || nil
  @var3 = get_string_value || nil

  # there are many more values, any of them might be nil
end

When I convert these values into a JSON object in a view, the nil values end up being rendered as empty spaces:

:javascript
  window.MyObj = {
    var1: #{@var1},
    var2: #{@var1},
    var2: #{@var3}
  }

The problem is that when a value is nil, it is displayed as an empty space instead of nil itself.

:javascript
  window.MyObj = {
    var1: ,
    var2: 33,
    var2: 
  }

Any suggestions on how to fix this issue?

Answer №1

Avoid trying to create something that already exists. Utilize the JSON ruby standard library for json serialization:

require 'json'
json = {var1: nil, var2: 42, var2: nil}.to_json
#⇒ "{\"var1\":null,\"var2\":42,\"var3\":null}"

After that:

:javascript
  window.MyObj = json

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

I encountered a PrimeVue error while running a Vue Jest test

When working on a Vue jest test, I encountered an error message "No PrimeVue Confirmation provided!" which seemed to be related to the useToast() and useConfirm() services. "transformIgnorePatterns": [ "<rootDir>/node_modules/(?! ...

Guide on transferring Javascript array to PHP script via AJAX?

I need to send a JavaScript array to a PHP file using an AJAX call. Here is the JavaScript array I am working with: var myArray = new Array("Saab","Volvo","BMW"); This JavaScript code will pass the array to the PHP file through an AJAX request and displ ...

Issue Parsing JSON Information - Asynchronous Operation

I encountered an issue with the message Error parsing Data when handling exceptions while parsing JSON data in my main code block. The error No Data Found is not being captured within the JSONException, leading me to believe that the database query is suc ...

Substitute an item with another -JavaScript

While I understand this is a rather common question, my search through various sources has yielded answers that involve libraries, ES6, or methods not supported by native JavaScript. My goal is to simply replace one object with another based on a condition ...

Display One Div at a Time in Sequence on Page Load Using jQuery

I have come across this question multiple times: How to Fade In images on page load using JavaScript one after the other? Fade in divs sequentially Using jQuery .fadeIn() on page load? Despite trying various recommended methods, I'm still unable t ...

Extracting the value of an attribute from an XML element and converting it into an HTML unordered list with

Here is an example of an xml file structure: <root> <child_1 entity_id = "1" value="Game" parent_id="0"> <child_2 entity_id="2" value="Activities" parent_id="1"> <child_3 entity_id="3" value="Physical1" parent_id="2"> ...

Use an if-else statement in jQuery with selectors to determine if a specific div element has been added to it

What if you have a main div and append one of these sub-divs to it? For example: <div class ="append"> <div id ="one"></div> <div id ="two"></div> </div> Then in jQuery, could you do something like this: if ($(.a ...

Detecting the length of nested structures in JSON using Angular Views

Illustrative JSON Format { "holding": [ { "company": 1, "employee": [ { "id": 1, "name": "John"}, { "id": 2, "name": "Michael"}, { "id": 3, "name": "George"} ] }, { "company": 2, "employe ...

Travel to the root route of one BrowserRouter from a different BrowserRouter and encounter the message: "Warning: Maximum update depth exceeded."

When transitioning from one BrowserRouter to another BrowserRouter, the error message "Maximum update depth exceeded" is appearing. Caution: The maximum update depth has been surpassed. This issue can arise when a component calls setState within useEffec ...

Verify whether a certain key exists within the gun.js file

Suppose I need to verify whether a specific entry exists in the database before adding it. I attempted the following: gun.get('demograph').once((data, key) => { console.log("realtime updates 1:", data); }); However, I only receive ...

Using the window.history.pushState function triggers a page reload every time it is activated

I've been attempting to navigate from page to page without the need for a reload. I came across suggestions that using window.history.pushState() could achieve this, however, it appears that the page is still reloading. Furthermore, an attempt ...

Creating dynamic button names and detecting the pressed button in PHP

Right now, I am experimenting with PHP to create a unique project. This experiment is just a small part of a larger file that I am working on. Essentially, the aim is for the program to generate a series of submit buttons within a form, each assigned a dis ...

Implementing a Tab on Firefox Extension Upon Window Load

I have a requirement to add a tab whenever a new Firefox window is loaded for my bootstrap extension. Below is the code snippet I am using: var WindowListener = { setupBrowserUI: function(window) { window.gBrowser.selectedTab=window.gBrowser.a ...

SSL Offloading and Cross-Origin Resource Sharing

I am currently facing a challenge with my two applications located on separate servers. One acts as the frontend machine while the other serves as the backend API. Our setup involves SSL termination at the load balancer for security. The issue arises when ...

How to eliminate the ng-component tag from an Angular 8 table row template

I currently have a dynamic table component with 2 modes: Normal table - functioning properly Custom Row Template - encountering issues due to Angular adding the <ng-component> tag The logic within the TableComponent is not the main concern, it&apo ...

Attempting to extract the desired aggregations from a two-dimensional JSON array

Looking to parse through this JSON 2D array (snapshot data example below) to calculate the total cases and deaths for each date, disregarding the state column. While achievable in SQL, it poses a challenge in JavaScript. Ultimately, the summarized data wi ...

Adjusting Chart.js line graph alignment to the left

I'm curious about why my chart is not aligned to the left and how I can fix this issue. Here is the code snippet I am working with: var data = { labels: ["ID"] , datasets: [ { label: "Sensor 1" , data: [{ ...

Saving extra parameters with MongooseJS

When saving data in my app using a POST query, how can I include additional parameters to the Item? For example, I would like to add user: req.user._id. var Item = new Model(req.body); Item.save(function (err, model) { res.send(model); }); ...

Why is the Axios instance/function not being passed the argument?

I am currently working on refactoring a next.js App that has a functioning axios call. However, I have encountered an issue with my new function not receiving arguments. The problem consists of two main components: my next.js page and an external custom m ...

Managing a large number of records in a for loop on a Node.js server can be challenging, especially when dealing with nearly

After setting up a NodeJS server and connecting it to a MySQL database with around 5000 users, I needed to read the data from MySQL and update a MongoDB database. I managed to write code for this process. https://gist.github.com/chanakaDe/aa9d6a511070c3c78 ...