0

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.

2
  • that isn't valid JSON - see json.org - it would need to be {"id":"abc","name":"abc","24h_total":"370029.0","last_updated":"1501633446"} .. note ... all keys and all strings enclosed in "..." ... '...' is not valid JSON Commented Aug 2, 2017 at 0:56
  • Oh, wait, I see, you've misrepresented the actual JSON you have ... yes, it's the fact that variable names in JS can't start with a digit Commented Aug 2, 2017 at 1:00

2 Answers 2

2

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

console.log(jsondata[i]['24h_total']);
Sign up to request clarification or add additional context in comments.

Comments

0

Access that property like so:

jsondata[i]['24h_total']

This will fix the error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.