2

This is the data I fetch through an API:

{ "0x5af2be193a6abca9c8817001f45744777db30756": { "usd": 0.11039 }}

but when I try to access the data to put in html using:

var price = data.0x5af2be193a6abca9c8817001f45744777db30756.usd;

The error reads back:

Uncaught SyntaxError: Invalid or unexpected token

I think it is bc it doesn't identify 0x5af2be193a6abca9c8817001f45744777db30756
as a string but I don't know how to fix it.

2
  • You can use data["0x5af2be193a6abca9c8817001f45744777db30756"].usd; instead, however it's probably not a good idea to be hard coding such strange keys in your code, perhaps you want to loop over the data such as with a for in ... loop. Commented Oct 10, 2020 at 1:17
  • Thank you! & thx for the suggestion! Commented Oct 10, 2020 at 1:30

2 Answers 2

2

Try this code below:

var price = data["0x5af2be193a6abca9c8817001f45744777db30756"].usd;
Sign up to request clarification or add additional context in comments.

Comments

1

According to the JavaScript MDN Documentation for Objects and Properties

"An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation."

Your key '0x5af2be193a6abca9c8817001f45744777db30756' is an invalid identifier because it starts with a number. You can access it using square bracket notation:

var price = data["0x5af2be193a6abca9c8817001f45744777db30756"].usd;

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.