Could converting a 47-byte JSON string into 340 MB be possible through JSON stringification?

var keys = [7925181,"68113227"];
var vals = {"7925181":["68113227"],"68113227":["7925181"]};

var temp = [];
for (var i = 0; i < keys.length; i++) {
    temp[keys[i]] = vals[keys[i]];
}
//alert(JSON.stringify(vals).length);
alert(JSON.stringify(temp).length);

After running this script in my Chrome browser, I was surprised to see an output of 340666156 after some time.

This raises the question... how did that happen?

The commented out alert function gives an output of 47. Shouldn't the second alert show a similar result? Isn't temp supposed to be a duplicate of val?

You can find a jsfiddle with the code here:

http://jsfiddle.net/vMMd2/

Additionally, if you want to test browser crashes (Chrome crashed for me), you can add the following snippet at the end:

temp.forEach(function(entry) {
    alert(temp);
});

Any thoughts or insights on this issue?

Answer №1

const items = [10581223,"32197654"];
const data = {"10581223":["32197654"],"32197654":["10581223"]};

const temporaryData = {};
for (let index = 0; index < items.length; index++) {
    temporaryData[items[index]] = data[items[index]];
}
//alert(JSON.stringify(data).length);
alert(JSON.stringify(temporaryData).length);

http://jsfiddle.net/zerkms/vMMd2/2/

By creating a sparse array, V8 may initialize all the gaps with certain values like undefined (as discovered by nnnnnn). This process takes some time.

Answer №2

According to @zerkms, this situation is occurring for a reason. However, I also wanted to highlight why it's happening.

> var temp = [];
> temp[10] = 'test';
> temp 
[ , , , , , , , , , , 'test' ]

It's evident that 9 undefined values are being created. When I executed the above code with nodejs, the null values were not visible.

If I were to use JSON.stringify(), the result would be:

> JSON.stringify(temp)
'[null,null,null,null,null,null,null,null,null,null,"test"]'

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

Sharing information with Django through Ajax and jQuery

I'm facing an issue with posting html5 geolocation data to the django admin backend. I've managed to display the latitude and longitude on the html page but can't seem to successfully submit the data to django. I suspect there might be a pro ...

Alter the font color of text using JavaScript in an HTML document

I am struggling to change the title color in my HTML code below, but the text color does not seem to be changing. How can I make this adjustment? /** * Generate a HTML table with the provided data */ Highcharts.Chart.prototype.generateTable ...

Utilizing JavaScript For Loops for Code Repetition

Apologies for the ambiguous question title - struggling to articulate this properly. Essentially, I have some JavaScript code that I am looking to streamline by using a for loop. $('.q1').keyup(function () { if ($.inArray($(this).val().toLo ...

An array filled with unique and non-repeating elements

I want to display random country flags next to each other, making sure they do not match. However, my specific case requires a unique solution for dealing with arrays: function displayRandomFlags() { var flagurls = ["ZPlo8tpmp/chi","cJBo8tpk6/sov","QyLo ...

Footer button overrides list components due to improper implementation of vertical ion-scroll

Having some trouble setting up ion-scroll on a specific screen in my mobile application built with Ionic. On the Book page of my app, I'm encountering two main issues: https://i.stack.imgur.com/MnheG.png 1) The placement of the Confirm button doesn& ...

Encountered an issue while trying to implement CORS using yarn

Currently experiencing the following issue: Error message: An unexpected error occurred "/home/vagrant/.cache/yarn/v1/npm-cors-2.8.4-2bd381f2eb201020105cd50ea59da63090694686/.yarn-metadata.json: Unexpected end of JSON input". Some important points to c ...

Ways to pass data to a different module component by utilizing BehaviourSubject

In multiple projects, I have used a particular approach to pass data from one component to another. However, in my current project, I am facing an issue with passing data from a parent component (in AppModule) to a sidebar component (in CoreModule) upon dr ...

What is the reason for Jquery AJAX appending additional path to the relative path?

I am encountering an issue with the following code snippet $.ajax({ url: "search/prefetch", success: function (data) { $(".result").html(data); alert("Load was performed."); }, dataType: "json" } ...

What is the best way to trigger a function when a button is enabled in Angular 8?

Here is a portion of my sign-in.component.html file. I have created a function in the corresponding sign-in.component.ts file that I want to trigger when the button below becomes enabled. Here is an example of what I am trying to achieve: <div class= ...

Is there a way to retrieve two separate route details using jQuery simultaneously?

Clicking the checkbox should display the Full Name: input type="text" id="demonum" size="05"> <button type="button" onclick="load_doc()">click</button><br><br> <input type="checkbox" id ="check" > The r ...

Creating a private variable in Javascript is possible by using getter and setter functions to manage access to the

Is this the correct way to simulate a private variable? var C = function(a) { var _private = a + 1; // more code... Object.defineProperties(this, { 'privateProp': { get: function() { return _privat ...

Displaying the focus icon on the active tab using Angular Material

I am currently utilizing Angular material to dynamically generate tabs in my HTML code. I'm trying to display a drop arrow icon on the active or selected tabs, but I am facing some challenges with the implementation. Below is the code snippet I have ...

Conceal the information beneath a see-through fixed navigation bar when scrolling downward

the issue: I am facing a challenge with my transparent fixed navbar that has a margin-top gap. The content below the navbar needs to be positioned under it while scrolling down, but the background of the page is a dynamic slideshow of various images. This ...

REACT performance impacted by slow array filtering

I have a custom listbox feature, where a div holds a vertical list of other div elements. There is also an input field for searching within the list. While it works fine with small data sets, it becomes extremely slow with large amounts of data. In additi ...

Transforming ASCII character representations in UTF-8 encoding to unique special characters

After scouring the web, I have come across numerous questions similar to mine, but none of them quite fit my specific issue. The problem arises when using a third-party JSON web API, as the JSON response sometimes contains special characters that are inco ...

Utilizing Jackson JSON keys as values within a class

Is there a way to extract keys from a JSON document and use them as values in a Java class without relying on Map? Consider the following JSON structure: { "GateWay": { "API1": { "Infos": "More", "Meta": [1,2,3] }, "API2": { "Infos": "E ...

Using Perl to pass query information with ajax/json and including scalar reference for DBIx::Class

I am currently facing an issue while trying to pass a query from jquery/ajax/json to a perl script that utilizes DBIx::Class and returns the results. While I have no trouble getting a basic query to function, I encounter difficulties when needing to includ ...

Update the browser value using AJAX without the need to refresh the page

After retrieving a value from an XML file using ajax jquery, I encountered an issue. When I change the value in my XML file, it does not automatically update in the browser. <?xml version="1.0"?> <count><number>5</number></count ...

Enhancing Efficiency with Laravel 5: Updating Multiple Data Entries

My Simple Todo App lacks the ability to persist multiple record updates simultaneously. The client-side version can be found here: http://codepen.io/anon/pen/bVVpyN Whenever I perform an action, I send an HTTP request to my Laravel API for data persistenc ...

Can you explain the distinction between String[] and [String] in TypeScript?

Can you explain the distinction between String[] and [String] in typescript? Which option would be more advantageous to use? ...