Kelvin U
Kelvin U

Reputation: 353

JSON.parse SyntaxError: Invalid or unexpected token

Trying to parse this data:

{ id: 'abc',
    name: 'abc',
    '24h_total': '370029.0',
    last_updated: '1501633446' }

Trying to run this code on the above rest api response.....

var jsondata =  JSON.parse(body);
var values = [];
console.log(jsondata);

for(var i=0; i< jsondata.length; i++){
     //how do i access this property?
     console.log(jsondata[i].24h_total);
}

at the moment i get an error

    jsondata[i].24h_total, 
               ^^^

SyntaxError: Invalid or unexpected token

I am sure it's due to the fact that this field name starts with a number.

thanks in advance.

Upvotes: 0

Views: 1085

Answers (2)

Evan Trimboli
Evan Trimboli

Reputation: 30082

You need to access the property like so, because it's not a valid javascript identifier:

console.log(jsondata[i]['24h_total']);

Upvotes: 2

sg.cc
sg.cc

Reputation: 1816

Access that property like so:

jsondata[i]['24h_total']

This will fix the error.

Upvotes: 0

Related Questions