Neha Gupta
Neha Gupta

Reputation: 1067

Uncaught SyntaxError: Unexpected token [ with JSON.parse

I am trying to parse a string, coming from HTTP. The string looks like

[
    {
        "apiVersion": "ocs.openshift.io/v1alpha1",
        "kind": "StorageCluster",
        "metadata": {
            "name": "example-storagecluster",
            "namespace": "openshift-storage"
        },
        "spec": {
            "manageNodes": false
        }
    },

 ]

Parsing this string gives this error:

Uncaught SyntaxError: Unexpected token [ with JSON.parse

Can someone help me how to parse this string and get the value inside [ ]. Thanks in advance.

Upvotes: 0

Views: 314

Answers (3)

Telmo Dias
Telmo Dias

Reputation: 4168

That is not a valid JSON document. You can always use https://jsonlint.com/ to validate your documents if you don't have any other way.

In your case you have 1 comma too much in your JSON document:

[
    {
        "apiVersion": "ocs.openshift.io/v1alpha1",
        "kind": "StorageCluster",
        "metadata": {
            "name": "example-storagecluster",
            "namespace": "openshift-storage"
        },
        "spec": {
            "manageNodes": false
        }
    }
]

enter image description here

Upvotes: 0

Paflow
Paflow

Reputation: 2347

The Comma after the last } is not allowed.

Upvotes: 1

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7949

Here is the code. I executed in background script and it gives values correctly

var string = '[{"UserID":"10001","Name":"Ram"},{"UserID":"10002","Name":"Sultana"},{"UserID":"10003","Name":"Lakshmi"}]';


var parser = new JSONParser();
var parsedData = parser.parse(string);
var length = parsedData.length;

gs.print(length);



for(var i=0;i<length;i++){

gs.print(parsedData[i].UserID); 
gs.print(parsedData[i].Name);

}

Mark Correct if this solves your issue and also hit Like and Helpful if you find my response worthy based on the impact.

Upvotes: 0

Related Questions