Exploring the capabilities of JSON.stringify in Internet Explorer 11

I encountered a puzzling issue with my JavaScript code – it works flawlessly in Google Chrome 49.0.2623, but causes my entire file to crash in Explorer 11. The problem arises when I attempt to 'Export' JavaScript objects using AJAX. Let me share the snippet of code in question:

When running in Chrome:

function AjajPostComponentLists()

{

  var myFileContent = new Uint8Array();

   var aList1 = {FixedItems:1, List:["None", "Relay #1", "Relay #2"]};
   var aList2 = {FixedItems:1, List:["None", "Input #1", "Input #2", "Input #3", "Input #4", "Input #5"]};
   var aList3 = {FixedItems:1, List:["None", "Door #1", "Door #2"]};

   // ... (I won't list them all)

   myFileContent = JSON.stringify({aList1, aList2, aList3});

   // ...
}

The resulting output is as follows:

{"aList1":{"FixedItems":1,"List":["None","Relay #1","Relay #2"]},"aList2":{"FixedItems":1,"List":["None","Input #1","Input #2","Input #3","Input #4","Input #5"]},"aList3":{"FixedItems":1,"List":["None","Door #1","Door #2"]}}

However, when attempting to run this in Explorer 11, an error message surfaces:

SCRIPT1003: ':' expected

Interestingly, the error citation points towards the ternary operator, which seems unrelated.

I made an alternate tweak by replacing curly brackets with square brackets and managed to bypass the error, albeit sacrificing certain attributes like object names in the process.

What could be causing this discrepancy between Chrome and IE? Any insights would be greatly appreciated.

Thank you!

Answer №1

One issue that arises is the lack of support for ES6 object literal extensions in Internet Explorer (source). For example:

var text = 'some text';
var obj = { text };
console.log(obj); // { text: 'some text' }

To resolve this, you need to explicitly declare the property name for each variable:

myFileContent = JSON.stringify({
    aList1: aList1,
    aList2: aList2,
    aList3: aList3
});

To simplify this process when dealing with multiple aListX variables, consider using an array approach:

// Instead of aList1 = x, aList2 = y, let's create an array of lists
var aList = [];
aList.push({FixedItems:1, List:["None", "Relay #1", "Relay #2"]});
aList.push({FixedItems:1, List:["None", "Input #1", "Input #2", "Input #3", "Input #4", "Input #5"]});
aList.push({FixedItems:1, List:["None", "Door #1", "Door #2"]});

// ...

var aListObj = {};
for (var i = 0; i < aList.length; i++) {
    aListObj['aList' + (i + 1)] = aList[i];
}

myFileContent = JSON.stringify(aListObj);

By utilizing this method, you can avoid manually typing out each variable and achieve the desired output through iteration.

Answer №2

Thanks for your input, it has greatly improved my code as well as resolved the compatibility issues with IE. Here is a summary of the changes made:

  1. Created a global array of objects:

var aEditableObjects = { Relay : {FixedItems:1, List:["None", "Relay #1", "Relay #2"]}, Input : {FixedItems:1, List:["None", "Input #1", "Input #2", "Input #3", "Input #4", "Input #5"]}, Door : {FixedItems:1, List:["None", "Door #1", "Door #2"]} };

  1. Stringified the array and sent it via AJAX

    myFileContent = JSON.stringify(aEditableObjects);

    myFileContent = encodeURI(myFileContent); // Optional, to handle special characters

  2. Retrieved the data through AJAX

    try{aEditableObjects = JSON.parse(decodeURI(xmlhttp.responseText));}catch(e){AjajError("AjajGetComponentLists");}

Answer №3

Experiment with

JSON.stringify([array1, array2, array3]);
and consult the documentation for more information on JSON.stringify

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

What could be causing the failure of the update for this computed property in my Vue 3 application?

Currently, I am in the process of creating an audio player using Vue 3 and the Napster API. About the Project I have managed to make the vinyl rotate by utilizing a CSS keyframes-based animation paired with the computed property isSpinning. I intend for ...

Error message "Connection refused because of timeout duration exceeded"

File "/home/abhigenie92/stanford2/Code/dependencies.py", line 18, encountering error in the get_dependencies function: result = loads(server.parse(sentence)); File "/home/abhigenie92/stanford-corenlp-python/jsonrpc.py", line 934, while making a call ...

What is the best method to delete an element from an array that contains specific characters?

I am looking to filter out specific values from an array. var array = [<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2149444d4d4e615840494e4e0f424e4c">[email protected]</a>, www.hello.com, <a href="/cdn-cgi/l ...

What are some ways to enhance the functionality of the initComplete feature in Dat

$('#example').dataTable( { "initComplete": function(settings, json) { alert( 'DataTables has finished its initialisation.' ); } } ); Is there a way to extend the initComplete function for other languages? $.extend( true, $.f ...

Ways to resolve the error "Expected an assignment or function call but found an expression with no-unused-expressions"

Issue : Error in ./src/components/main.js Line 7: No function call or assignment found, only an expression is present (no-unused-expressions) Search for the specific keywords to get more information on each error. import React from 'react'; ...

Using MongoDB's distinct command with regular expressions

Utilizing MongoDB's distinct command has proven to be extremely valuable for obtaining a unique set of results based on a specific key within a collection. I have come across information indicating that this command supports regex, but I am strugglin ...

Achieving synchronous function execution with a single click in React

In my current project, I am utilizing ReactJs and Redux. I have encountered a scenario where I need to trigger two functions sequentially with just one click on the mainfunc(). The second function should only execute after the first function has complete ...

What is the method for determining the dimensions of the rectangle that the camera can capture at a specific location?

In my latest project, I developed a small three.js application that showcases the movement of multiple circles from the bottom to the top of the canvas: let renderer, scene, light, circles, camera; initialize(); animate(); function initialize() { re ...

Working with json, lists, and dictionaries in Python

Apologies for the extensive content, but I wanted to provide all necessary details. I am in the process of extracting specific data points from a JSON file with the following structure: { "count": 394, "status": "ok", "data": [ { ...

Exploring Angular 6's nested routes and corresponding components for child navigation

I'm currently diving into the concept of lazy loading in Angular 6. Here's a visual representation of the structure of my application: ─src ├───app │ ├───components │ │ ├───about │ │ ├─── ...

Encountering a CORS blockage: The request header authorization is restricted by Access-Control-Allow-Headers in the preflight response

I encountered an error message that says: Access to XMLHttpRequest at 'http://localhost:4000/api/investments' from origin 'http://localhost:5000' has been blocked by CORS policy: Request header field authorization is not allowed by Acce ...

The React route fails to display until clicked upon

Struggling with integrating React Router into my Electron desktop app for navigation. During debugging, I realized that the login component, which doesn't use routers, transitions smoothly to a component with a router. However, this new component fail ...

What is the best way to handle this situation using Python?

My current task involves utilizing an API that provides a JSON string with a specific format: {u'inboxMessages': [{u'fromAddress': u'BM-2DBYkhiBZCyrBa8J7gFRGrFRSGqtHgPtMvwQ', u'toAddress': u'BM-2DC7SCTj2gzgrGgM ...

Enhanced MUI TextField component with active cursor and focused state

When using the MUI TextField component as a single input form, I encountered an issue where the component loads with focus but no visible cursor to begin typing. To start typing, the user must click into the input field or press the tab key, which then act ...

In an if conditional, the object keys are initially undefined, but I am able to access them within the if statement

I have an issue where I am comparing two JavaScript objects by stringifying them. The first object is easily accessible without calling the keys, so these comparisons work fine: if(JSON.stringify(response) == JSON.stringify(lastcmd)) if(JSON.stringify(res ...

New button attribute incorporated in AJAX response automatically

data-original-text is automatically added in ajax success. Here is my code before: <button type="submit" disabled class="btn btn-primary btn-lg btn-block loader" id="idBtn">Verify</button> $(document).on("sub ...

Attempting to console.log data from within useEffect, but unfortunately no information is being logged

function FetchUserAccounts() { const [userAccounts, setUserAccounts] = useState(); useEffect(() => { async function fetchUserAccountsData() { const response = await fetch( 'https://proton.api.atomicassets.io/atomicassets/v1/a ...

Aligning the Bootstrap 5 navbar dropdown to the right side

I'm having trouble getting a part of my navbar to align right in bootstrap 5. I've followed the new documentation, but I think I might be adding the text in the wrong place. Can someone assist me in moving my dropdown to the right side of the nav ...

Guide on making a Vue.js show/hide button for each element on a webpage

There is a feature to toggle between displaying "more" or "less" text, but currently the @click event affects all elements causing them to show all the text at once. I realize that I need to pass a unique value to distinguish each element, but I am curren ...

Why does the CSHTML button containing a JavaScript onclick function only function intermittently?

I've implemented a download button on a webpage that dynamically assigns an ID based on the number of questions posted. Below is the code for the button: <input data-bind="attr: { id: $index() }" type="button" value="Downlo ...