Does the Apps Script parser JSON.parse() incorrectly remove leading zeros from string object keys?

I am facing an issue with my Apps Script Web App where JSON data is being manipulated when I try to parse it. Specifically, keys with leading zeros are being altered (e.g "0123" becomes "123") during the JSON.parse() function call. It seems like the function is interpreting my string as an integer but still treating it as a string. Can anyone confirm if this behavior is expected?

To demonstrate the problem, consider the following script:

function jsontest() {
  var json = '{"0123":"foo", "bar":"0123", "foobar":123}';
  var test = JSON.parse(json);
  var check = ("0123" in test);
  var check2 = ("123" in test);

  Logger.log(test);
  Logger.log(JSON.stringify(test));
  Logger.log(check);
  Logger.log(check2);
}

The result logged is as follows:

[17-06-07 15:22:56:241 CDT] {123=foo, bar=0123, foobar=123}
[17-06-07 15:22:56:241 CDT] {"123":"foo","bar":"0123","foobar":123}
[17-06-07 15:22:56:242 CDT] false
[17-06-07 15:22:56:243 CDT] true

Answer №1

When working with Google Apps Script, the JSON.parse() function has a behavior where it removes single and double quotations. Additionally, if the keys contain numbers, they are automatically converted to numbers. For example, "0123" is changed to the number 123. One way to avoid this conversion is by using the eval() function. When eval() is used, the quotations are removed without altering the strings.

While this approach may not be considered the best practice, it is one option to consider.

Sample :

var json = '{"0123":"foo", "bar":"0123", "foobar":123}';

var test1 = JSON.parse(json);
var test2 = eval("json=" + json);

Logger.log("%s, %s", test1, JSON.stringify(test1));
Logger.log("%s, %s", test2, JSON.stringify(test2));

Result :

{123=foo, bar=0123, foobar=123}, {"123":"foo","bar":"0123","foobar":123}
{bar=0123, foobar=123.0, 0123=foo}, {"0123":"foo","bar":"0123","foobar":123}

By incorporating the changes suggested in the sample script above, your modified script would look like this:

Modified script :

function jsontest() {
  var json = '{"0123":"foo", "bar":"0123", "foobar":123}';
  
  var test = eval("json=" + json); // <-- Added
//  var test = JSON.parse(json);
  
  var check = ("0123" in test);
  var check2 = ("123" in test);
  
  Logger.log(test);
  Logger.log(JSON.stringify(test));
  Logger.log(check);
  Logger.log(check2);
}

Result :

{bar=0123, foobar=123.0, 0123=foo}
{"0123":"foo","bar":"0123","foobar":123}
true
false

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

Unable to locate the reverse for 'my_views_name' without any arguments in Django. Bridging server-side code with client-side JavaScript using jQuery

How can I create a button to update a URL after fetching data from the database using jQuery AJAX? This is my code in views.py: def list_maingroup(request): lists = MainGroup.objects.all().order_by('-pk') data = [] for i in lists: ...

Querying with Spring JPA - Dynamically passing the index for JSON_REMOVE function

I have been using the JSON_REMOVE method to remove a specific field from my JSON array column. Below is the JPA query I initially used: @Modifying @Transactional @Query("UPDATE Data d SET d.month = JSON_REMOVE(d.month, '$[0].revenue') " ...

What is the best way to toggle between rendering two components or updating two outlets based on a route in React Router?

There is a React application I am working on that utilizes React-Router. My layout component has the following structure: import React from 'react'; import Header from './components/Header/Header'; import Footer from './components/ ...

"Reasons Why I'm Unable to Retrieve the Length of an Array

Can someone lend a hand with finding the array length? I attempted to utilize Object.keys for this task { "@odata.context":"https://graph.microsoft.com/v1.0/$metadata#sites('volagas.sharepoint.com')/sites('volagas.sharepoint.com%2C9 ...

The onInvoke hook in Zone.js is receiving an inaccurate currentZone value

Greetings. In the comments for the ZoneSpec interface (found in zone.ts file), it states that the onInvoke hook must receive currentZone as the second parameter. If creating an interceptor zone, the reference to that zone should be passed as the second pa ...

Tips for bringing a particular tab into focus when a page initially loads

My webpage features custom links (tabs) that display content when clicked. By default, the first tab is selected and its content is shown, while the rest are set to display:none. Clicking on any other link will assign the 'selected' class to it, ...

Dealing with asynchronous tasks in JavaScript

I am currently delving into the world of Node development and struggling to grasp the asynchronous nature of JavaScript and Node.js. My project involves creating a microservices backend web server using Express in the gateway service, which then translates ...

Troubleshooting Problem with Retrieving Files Using jQuery Ajax

I am attempting to use ajax to retrieve the contents of a file, but it doesn't seem to be functioning properly. I'm not sure why this is happening, as I have copied the same code from the examples on w3schools.com. $().ready(function(){ ...

Issues with HTML marquee not functioning properly post fadeIn()

I am attempting to create a progress bar using the HTML marquee element. When the user clicks submit, I want to fadeIn the HTML marquee and fadeOut with AJAX success. However, when I click the submit button, the marquee does not fadeIn as expected. Here is ...

I'm interested in querying my mongodb collection data based on a particular field

I need help creating a list from my mongodb database that can be sorted by the "username" field. After learning about the limitations of namespaceing in mongodb, I'm trying to figure out how to sort my collection based on the "username" field. Here ...

`Error encountered when JSONP script is returning incorrect MIME Type`

I am currently faced with the task of extracting data from a third-party feed that provides a JSON file. Unfortunately, I do not have access to the server to enable CORS, so after conducting some research I learned about using JSONP. When checking the Chro ...

Retrieving JSON data by key through ajax does not show the expected output

I'm currently working with JSON data in the form of an array, and I'm facing some issues. Here's how the data looks: [ { "id": 1, "name": "Leanne Graham", "username": "Bret", ...

What is the best way to showcase a circular dot to indicate active status in a React component

In previous versions of react, the code displayed either "active" or "inactive" for a user. I now want to change it to display a small red or green dot instead. How can I achieve this? ...

What is the best way to locate the key with the greatest value in an array that is less than or equal to a certain

In my data structure, I have an array that maps user levels to the minimum points required for each level. Here's how it looks: $userLevels = array(0 => 0, 1 => 400, 2 => 800); The keys represent user levels and the values represent the min ...

Handling Errors in Asynchronous Functions with JavaScriptLet's explore the best practices for

I am a beginner in javascript and recently delved into async/await. After going through various resources, I gained a basic understanding. However, while experimenting with some code examples, I encountered unexpected results which left me puzzled about wh ...

Utilizing window.matchMedia in Javascript to retain user selections during page transitions

I am encountering difficulties with the prefers-color-scheme feature and the logic I am attempting to implement. Specifically, I have a toggle on my website that allows users to override their preferred color scheme (black or light mode). However, I am fac ...

Is it possible to include numbers and commas in JQuery Validation?

I have implemented a jQuery validation plugin to validate the fields of a form. One specific requirement is to validate a field to only allow commas and numbers. Below is the HTML code snippet: <input type="text" placeholder="Number of Employees" requ ...

Exploring creative solutions for generating PDFs with Node JS

Looking for a way to generate PDF Documents in Node.JS? Is there an alternative solution for organizing templates for various types of PDF creation? I've been utilizing PDFKit for creating PDF Documents on the server side with Javascript. Unfortunate ...

Top method for combining several external JavaScript libraries into a single one using webpack

Recently, I was diving into the world of webpack tutorial and it struck me that in order to combine everything into one module, scripts need to use require('./xyz'). Until now, I've always written individual scripts and loaded them in HTML u ...

tips on assigning a unique ID to an item in a firebase database collection

My code is structured like this: const userCollectionRef = collection(db, 'users'); Then I add data using the following method : const addInfoToDataBase = async () => { checkLike(); await addDoc(userCollectionRef, { likePost: us ...