0

I am no JavaScript expert, but after a long time of reading, experimenting and the power of Google and especially the results of stackoverflow I managed to work with the data of a REST API.

I made everything with CodePen, because it's nice to understand what I was doing. Now I came to a problem that I can't solve myself. I tried to google it, but I think I just don't know the right keywords.

My problem is a SyntaxError which only occurs in debug mode. But I think my main problem is, that I understand how to get all values and work with all Object.keys and Object.values but not the correct way to get 1 specific value.

Uncaught SyntaxError: Unexpected token '['

The JSON file looks like this:

[{"label":"Value","next":Value, ...},{"label":"Value","next":Value, ...}, ...]

My JavaScript Code looks like this:

const api_url = 'external json file';

async function getBrowsersData() {
    const response_api_url = await fetch(api_url_api_url);
    const data_api_url = await response_api_url.json();

    const data = data_api_url.[0].label;

The SyntaxError comes from the [0], what is the explained way here, if I understand it right. If I use ["0"] as described here, I get a SyntaxError in CodePen without Debug Mode.

Can someone please explain how I select the first label and, more importantly, why this works in CodePen, but not in its debug mode? A link with a detailed description would help me too. I know it's probably a very simple question, but I am stuck and out of keywords I could search.

I have read this excellent and very detailed answer several times, but I do not understand my mistake.

Barny
  • 3
  • 5

1 Answers1

0

Can you provide the codepen? It's hard to see exactly what you're doing wrong without full sample data

A quick issue I see is this though:

const data = data_browsers_30.[0].label;

should probably be:

const data = data_browsers_30[0].label;

That's the reason you get the SyntaxError; you don't need the . before [0].

if you think the label key is the issue this syntax is generally also valid:

const data = data_browsers_30[0]["label"]
ᴓᴓᴓ
  • 1,178
  • 1
  • 7
  • 18
  • 1
    Thank you very much! This was right: const data = data_browsers_30[0].label; I still don't understand why it was working inside the CodePen. – Barny Jul 15 '21 at 04:46