JavaScript: Encounter issues while parsing JSON due to encountering an unexpected token error

I was able to successfully parse a JSON URL using Java code in the past, but now I need to migrate it to JavaScript. However, when attempting to parse the JSON using JavaScript, I encountered a syntax error: Unexpected token i.

SyntaxError: Unexpected token i in JSON at position 2
at JSON.parse (<anonymous>)
at success (homeCtrl.js:1060)
at processQueue (ionic.bundle.js:29127)
at ionic.bundle.js:29143
at Scope.$eval (ionic.bundle.js:30395)
at Scope.$digest (ionic.bundle.js:30211)
at Scope.$apply (ionic.bundle.js:30503)
at done (ionic.bundle.js:24824)
at completeRequest (ionic.bundle.js:25022)
at XMLHttpRequest.requestLoaded (ionic.bundle.js:24963)
(anonymous) @ ionic.bundle.js:26794
(anonymous) @ ionic.bundle.js:23507
processQueue @ ionic.bundle.js:29135
(anonymous) @ ionic.bundle.js:29143
$eval @ ionic.bundle.js:30395
$digest @ ionic.bundle.js:30211
$apply @ ionic.bundle.js:30503
done @ ionic.bundle.js:24824
completeRequest @ ionic.bundle.js:25022
requestLoaded @ ionic.bundle.js:24963 

Below is my JavaScript code:

//scrap singapore
function topVolumeGainerLosersSingapore(type) {
$ionicLoading.show();

var url = "http://www.sgx.com/JsonRead/JsonData?qryId=RStock&timeout=30";

$http({
method: 'GET',
url: url,
transformResponse: undefined,
headers: {
"Content-Type":"text/plain",
"Accept":"text/plain"
}
}).then(function success(response) {
// this function will be called when the request is success
var text = response.data;
//console.log(text);
var replaceData = text.substring(text.indexOf("&&")+2);
//console.log(replaceData);
var newData = JSON.parse(replaceData);
console.log(newData);

}, function error(response) {
// this function will be called when the request returned error status
$ionicLoading.hide();
console.log(response);
});
}

The Java code is shown below and can parse the same URL correctly without any errors:

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new AsyncTas().execute();
    }

    private class AsyncTas extends AsyncTask<Void,Void,Void>{

        @Override
        protected Void doInBackground(Void... voids) {
            HttpURLConnection urlConnection = null;
            String urlString = "http://www.sgx.com/JsonRead/JsonData?qryId=RStock&timeout=30";
            try {
                urlConnection = (HttpURLConnection) new URL(urlString).openConnection();
                //String result = readIt(new BufferedInputStream(urlConnection.getInputStream()));
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(urlConnection.getInputStream()));

                // Grab the results
                StringBuilder log = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    log.append(line + "\n");
                }
                String result = log.toString();

                result = result.substring(result.indexOf("&&") + 2);
                JSONObject jo = new JSONObject(result);

                Log.e(TAG, "doInBackground: "+result);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(),"Unable to parse json "+e.getMessage(),Toast.LENGTH_LONG).show();
            }
            return null;
        }
    }
}

The desired output from parsing the JSON data should look like this:

{identifier:'ID', label:'As at 08-03-2017 2:48 PM',items:[{ID:0,N:'3Cnergy',SIP:'',NC:'502',R:'',I:'',M:'t',LT:0.000,C:0.000,VL:0.000,BV:100.000,B:'0.042',S:'0.047',SV:70.000,O:0.000,H:0.000,L:0.000,V:0.000,SC:'2',PV:0.040,PTD:'20170307',BL:'100',EX:'',EJ:'',CLO:'',P:0.0,P_:'X',V_:''},{ID:1,N:'800 Super',SIP:'',NC:'5TG',R:'',I:'',M:'t',LT:1.160,C:-0.020,VL:51.400,BV:10.500,B:'1.160',S:'1.170',SV:10.000,O:1.180,H:1.180,L:1.160,V:60324.500,SC:'A',PV:1.180,PTD:'20170307',BL:'100',EX:'',EJ:'',CLO:'',P:-1.694915234375,P_:'X',V_:''},{ID:2,N:'8Telecom',SIP:'',NC:'AZG',R:'',I:'',M:'',LT:0.000,C:0.000,VL:0.000,BV:5.000,B:'0.130',S:'0.140',SV:10.000,O:0.000,H:0.000,L:0.000,V:0.000,SC:'2',PV:0.135,PTD:'20170306',BL:'100',EX:'',EJ:'',CLO:'',P:0.0,P_:'X',V_:''},{ID:3,N:'A-Smart',SIP:'',NC:'BQC',R:'',I:'',M:'',LT:0.570,C:-0.020,VL:60.000,BV:31.000,B:'0.570',S:'0.580',SV:10.000,O:0.575,H:0.575,L:0.570,V:34350.000,SC:'2',PV:0.590,PTD:'20170307',BL:'100',EX:'',EJ:'',CLO:'',P:-3.38983046875,P_:'X',V_:''},

Answer №1

It appears that the source data does not contain valid JSON information. As noted on http://json.org/, keys in JSON must be wrapped in double quotes and this also applies to string values:

{ "identifier": "ID" }

The error message indicates that the parser was anticipating a double quote instead of the 'i' character.

I recommend testing your code with a small snippet to confirm it can handle valid JSON properly.

Answer №2

To handle your JSON data that is not in strict mode, consider using eval instead. In a strict mode JSON data, the keys must be double-quoted.

Examples

var jsonData = "{} && { identifier: 'ID' }";

function test(jsonData, parser){
  try{
    console.log("Parsing with "+parser.name+" => "+JSON.stringify(parser("("+jsonData+")")));
  }catch(e){
    console.log('Cannot parse with '+parser.name);
  }
}
test(jsonData, JSON.parse);
test(jsonData, eval);

Strict Mode Support in JSON.parse Only

var formats={
 strict:'{"foo":"bar"}',
 'single-quotes':"{'foo':'bar'}",
 'no-quotes':"{foo:'bar'}"
};

function test(parser){
  return parser.name+" supports " +Object.keys(formats).reduce(function(supports,format){
    try{
       parser(formats[format]);
       supports.push(format);
    }catch(e){      
    }finally{return supports;}
  },[]);
}
function parseJSON(json){
 return eval("("+json+")");
}
console.log(test(parseJSON));
console.log(test(JSON.parse));

Enhancing Security by Encapsulating eval()

window.$ = window.jQuery = {};
function foo() {
    return 'bar';
}

parse = (function () {
    //disable all global keys
    eval("var " + Object.keys(window).join(', '));

    return function (_) {
        return eval("(" + _ + ")");
    };
})();


var snippets = [
    "window",
    "location",
    "$",
    "jQuery",
    "location.href='http://www.example.com'",
    'local',
    "{foo:'bar'}",
    "foo()",
    "eval('window')",
    'function ref(){return window}()'
];
snippets.forEach(function (snippet) {
    var local = 'local value';
    var expression = "parse(" + JSON.stringify(snippet) + ")";
    try {
        console.log(expression + " => " + JSON.stringify(parse(snippet)));
    } catch (e) {
        console.error(expression + " failed!");
    }
});

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

Can double curly braces be added within an HTML attribute when using Vue?

Suppose I would like to include <input value='{{default}}'></input> in regular HTML. This will display a textbox with {{default}} as the default input. However, when attempting to achieve the same thing with Vue, it does not work as ...

What causes the removeChild function to exhibit distinct behaviors when it comes to list items versus i tags?

It has come to my attention that the removeChild function does not behave in the same way with all elements, particularly when dealing with list items. I am currently using the i tag for icons from frontAwesome and would like to individually remove these i ...

What is the best way to execute a group by operation on a collection of JSON objects in Python?

Currently, I am tackling a Python script that involves grouping by a key within a list of JSON objects. In my Python code, I have access to an extensive array of JSON objects structured like this: [{'name': xyz, 'territory': abc, ...

Removing zeros from a one-dimensional tensor in TensorFlow.js: A step-by-step guide

If I have a 1D tensor (distinct from an array) with the values [0,2,0,1,-3], my goal is to retrieve only the non-zero values. Using the example provided, I want to receive [2,1,-3] as the output. Is there a way to achieve this in TensorFlow.js? ...

Discovering the bottom side of a cube using Euler Angles (or Quaternions) in three.js

Hey there! I have a little puzzle that I could use your help with: Imagine this - I've got a cube that can be rotated around three different axes. I've gathered some data on the cube's rotation, specifically an array of three angles rangi ...

Issue with Flask and JS: Syntax error detected - Unexpected token '<'

The Flask web app is currently working on fetching data from a database table and displaying it in HTML format using a JavaScript file that handles this operation. This whole process is integrated within a single Flask application. I've attempted to ...

The EditText class instantiated with an android.content.Context parameter cannot be used with an android.view.View parameter

To bolster the security of my app, I decided to create a username and password for authentication purposes. However, I hit a roadblock when trying to define them as objects, resulting in the error mentioned above. Any insights or advice on how to tackle t ...

Issue with Android Post to API not resolved, however Ajax Post is functioning correctly. The necessary string parameter 'firstname' is missing

Despite having a functional Spring Framework API setup for receiving GET/POST requests on the web, I encountered an issue when attempting to post from an Android device. The error message "Required String parameter 'firstname' is not present" kep ...

The capability to scroll within a stationary container

Whenever you click a button, a div slides out from the left by 100%. This div contains the menu for my website. The problem I'm encountering is that on smaller browser sizes, some of the links are hidden because they get covered up. The #slidingMenu ...

Selenium unable to locate element within cache

I am encountering an issue with opening multiple URLs in the same browser session using Selenium. After executing the code below, only the first URL is being opened and then an error occurs. findElements = driver.findElements(By.xpath("//*[@id='searc ...

Ways to provide information to an rxjs observer

It appears that most people find observers to be a piece of cake, but I personally struggle with them. I am trying to set up an observable that can receive a number input after it has been created, triggered by pressing a button. However, all the examples ...

Securing Credit Card Numbers with Masked Input in Ionic 3

After testing out 3-4 npm modules, I encountered issues with each one when trying to mask my ion-input for Credit Card numbers into groups of 4. Every module had its own errors that prevented me from achieving the desired masking result. I am looking for ...

Implementing a soft transition to intl-tel-input plugin

This tel-input plugin was developed by Jack O'Connor. You can find the plugin here: https://github.com/Bluefieldscom/intl-tel-input I have observed that the flags take approximately one second to download, and I would like to enhance this process wi ...

Utilize the "don't get terminated" app

Currently, I am working on implementing a middleware in my application to check for the presence of a token on all routes. For testing purposes, I have decided to focus on the /users route. In order to achieve this, I made the following adjustments to my a ...

adjust time in jQuery AJAX request when a button is clicked

I have the following code snippet that triggers when a button is clicked. When a user clicks on a button, I want to show a progress bar or waiting image in the browser for 5 seconds. How can I set a timeout and display the progress bar or waiting image wh ...

Adjusting mesh rotation on elliptical curve using mousewheel scrolling

I have arranged several plane meshes in a uniform manner along an elliptical curve. During the animation loop, I am moving them along the ellipse curve using curve.getPointAt with time delta and applying the matrix. Additionally, I am attempting to incor ...

Tips for successfully transferring the nested service and retrieving the response from an Angular factory to a controller

After making the Http Request and receiving the response from the first Service call, I then pass that response from the first service into the second service and receive the response back to the controller. Now that I have the response, I need to find a ...

Is it necessary to trim strings prior to employing the map function?

I am working on extracting all input values from a user-generated page and storing them in an array to make an ajax call for data processing. Here is my approach: $('#save').click(function(){ var data = $('*[data-array]').map(funct ...

Ways to identify and terminate a currently active Windows Process that is a Java application from within a separate Java application

If there is a windows process that happens to be a java application (java.exe), I am in need of closing it from another java application (a separate running .jar) which may also share the name java.exe on the windows taskbar. The typical approach to achie ...

react-router version 2.0 fails to direct traffic

I'm facing an issue with a piece of code that I have modified from the react-router project page. Despite my modifications, it doesn't seem to work as expected. Configuration In my setup, I have created several simple react components: var Ind ...