Unexpected identifier error encountered in iPhone IOS 10 Safari while attempting to parse JSON with the presence of the keyword "function

Currently, I am facing an issue while troubleshooting an error on a client's website that only seems to occur on iOS 10 devices. The clients have mentioned that it was working fine prior to upgrading their devices to iOS 10 and reverting back to iOS 9 eliminates the error. It seems like the problem is related to JSON.parse and local storage data (this.local[i]). Please see below for details on the javascript error, sample data, and JavaScript snippet.

Javascript Error:

[Error] SyntaxError: JSON Parse error: Unexpected identifier "function"
parse (Locus.js:40)

Data sample: (this.local)

[{"ObservationID":"444","Username":"blah","Deleted":0,"Flagged":0},
{"ObservationID":"555","Username":"blah","Deleted":0,"Flagged":0}]

Javascript:

Locus.prototype.loadFromLocal = function () {
    if (this.local) {
        for (var i in this.local) {
         var len = ('' + this.local[i]).split('{').length;
         if (len != 1) {
          this.data[i] = JSON.parse(this.local[i]);
         } 
         else {
             if (parseFloat(this.local[i]) == this.local[i]) {
                 /* local storage is a number */
                 this.data[i] = parseFloat(this.local[i]);
             } 
             else 
             {
                 /* already parsed */
                 this.data[i] = this.local[i];
             }
         }
    }
}

Answer №1

After some investigation, I discovered that IOS 10 has a tendency to terminate Javascript when an error occurs. The issue I encountered was due to the fact that my object (this.local) contained items of different types. While the first item was a JSON string, the second item happened to be a number. This caused an error when attempting to perform a split() operation on the second item. Interestingly, this error only occurred on IOS devices and did not affect common desktop/mac browsers.

To address this problem, I implemented a solution that involved checking the type of each item using typeof, along with a try catch block to handle both strings and JSON strings accordingly.

For more information on determining variable types, you can refer to:

To learn about differentiating between JSON and strings, check out: How to check if it's a string or JSON

if (typeof this.local[i] == 'number') 
{
    this.data[i] = parseFloat(this.local[i]);
}
else if (typeof this.local[i] == 'string')
{
    try
    {
        this.data[i] = JSON.parse(this.local[i]);
    }
    catch(e)
    {
        this.data[i] = this.local[i];
    }
}

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

Returning draggable elements to their original placement

I'm looking to create a custom function that resets my draggable elements to their original positions when invoked. This is not related to the built-in revert functionality. $('.drag').draggable({ stack: ".drag", snap: ".dro ...

What strategies can I use to dynamically update the .active class in jquery so it doesn't only target the initial one?

Utilizing bootstrap for tab-fade functionality has been successful so far. However, I am facing an issue when trying to select multiple active classes instead of just one. My current JQuery code only changes the text in the first element with the "active" ...

Avoiding HTML/JavaScript escape: Injecting database field content into DOM using jQuery

My goal is to integrate HTML and JavaScript code stored in a textfield of my database into my Rails application. The code looks like this: <script type="text/javascript"> document.write('<div id="test"></div>'); </script&g ...

Utilizing GSAP for crafting a dynamic horizontal scrolling section

I am currently working on creating a unique section that transforms into a horizontal scroller once the items (in this case, images) are visible, and then reverts to a vertical scroller once all the items have been scrolled through. My inspiration and ada ...

Customer Notification System Malfunctioning on Front End

I am currently experimenting with MeteorJS technology and attempting to use alerts for success or failure notifications when making a meteor call. However, I've encountered an issue where the alerts are not functioning as expected. T ...

What is the best way to link one element to another element?

Apologies for the mismatched title, but here's my issue: I need to create hidden checkboxes for each Polymer's paper-button div in jsp/style related problems. <%int i; %> <form ACTION="Computation.jsp"> <% for(i=0; i<n; ...

Consolidate JavaScript files into a single file using phpStorm

My goal with phpStorm is to consolidate multiple JavaScript files into a single one. To achieve this, I have integrated the closure compiler and set up the file watcher to minify each individual JavaScript file. Now my aim is to merge all of these JavaScr ...

Transferring binary data from C# to Node.js for deserialization

I am facing a challenge where I have a byte array created in C# from an object type, which is then sent over the socket protocol to a Node.js app. However, I am unable to deserialize the data into a readable object. Can anyone suggest a way to decode this ...

Using jQuery and JavaScript to swap images depending on the option chosen in a dropdown menu

On my existing ecommerce website, I have a dropdown menu with the following code: <select data-optgroup="10201" class="prodoption detailprodoption" onchange="updateoptimage(0,0)" name="optn0" id="optn0x0" size="1"><option value="">Please Selec ...

Utilize jQuery to choose a specific tab

I have implemented a jquery tab in my UI. I want to have the second tab selected when the page loads, instead of defaulting to the tab with the "Active" class. Here is my HTML tab code: <div class="typo"> <div class="container-fluid"> ...

JavaScript is displaying Not a Number (NaN) instead of the expected value

Currently, I am facing an issue with retrieving the user's work duration from a database column stored in minutes. My goal is to convert this value to HH:mm format to calculate the total hours worked per week, but I'm encountering obstacles. < ...

Issue with React Router: Trying to access the 'history' property of an undefined object

I am developing a styleguide app that features two dropdown components. Users can select both a brand and a specific component, and the app will display the chosen component styled according to the selected brand. I aim to have these options reflected in t ...

Using the `preventDefault` method within an `onclick` function nested inside another `onclick

I am currently working on an example in react.js <Card onClick="(e)=>{e.preventDefault(); goPage()}"> <Card.body> <Media> <img width={64} height={64} className="mr-3" ...

Searching for the location of a specific item within an array using

Trying to grasp the fundamental components of Javascript has led me to stumble upon a specific line of code: if (varX.indexOf(String(varY),0) < 0) In this scenario, varX represents an array of Strings and varY is one of the strings contained within th ...

The function toJson() does not exist for the specified stdClass object

After following a tutorial on implementing websockets in Laravel to create a live commenting system, I encountered an error that I cannot figure out. Even though I followed the code exactly as demonstrated in the video, this error persists. Does anyone hav ...

Issue with Panel Settings and Tooltip in Amcharts

Looking for solutions to two specific issues that I am struggling with: I have two charts with multiple panels, each having only one scroll bar. My problem lies with the balloon text - when hovering over a balloon, I need to display two different texts ...

Switch up the images based on the JSON response that is received

When receiving a JSON response, I am using the item details to populate a menu grid by utilizing an adapter. So far, I have successfully loaded all the item details such as ImageURL, Description, and Price. However, I encounter an issue when loading the is ...

Getting an unexpected empty response when submitting a request with a combination of image files and json parameters through postman, nodejs, and express

For my university project, I am developing a RESTful API for an online ticket shop that works across multiple platforms. I am using nodejs and express to create this API. First, I created the model for each event: const mongoose = require('mongoose&ap ...

Applying VueJS filters to refine object values

Is there a way to verify if the value of "startAt" is present in an object and return its corresponding ID? Here is the object in question: [{ "id": "1234567", "createTimestamp": "2020", "name": { "action": "", "allDay": false, "categor ...

Error encountered during Ionic iOS build caused by google-plus plugin

Seeking solution for the error below, unsure where to begin. While attempting to compile my Ionic project for iOS, encountering the following issue: $ ionic cordova build ios .... /Plugins/cordova-plugin-googleplus/GooglePlus.h:2:9: fatal error: 'Goog ...