Search code examples
arraysjsonapiurl

How to fix 'Private field must be declared in an enclosing class'


https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=d94b7d68284cbab1cdb7c2c3c81fd913&artist=kendrick+lamar&album=damn&format=json

The link above is a json file of an album and it has a URL of the album cover under the image section, but when I try extracting it, I get a syntax error telling me "Uncaught SyntaxError: Private field '#text' must be declared in an enclosing class".

For the code below, to get the large image, I would expect to do data.album.image[2].#text, but whenever I do this, I get an error telling me this: "Uncaught SyntaxError: Private field '#text' must be declared in an enclosing class" (screenshot here: https://gyazo.com/f6c9a16af02bda42313b4f369a753c33). Is this because of the number symbol? Because when I do data.album.image[2].size, I get an expected output of large. If so, how can I work around it?

async function getAlbum() {
        AlbumName = localStorage.getItem("textvalue");
        ArtistName = localStorage.getItem("textvalue2");

        AlbumName = AlbumName.replace(" ", "+");
        ArtistName = ArtistName.replace(" ", "+");

        const response = await fetch(
          "https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=d94b7d68284cbab1cdb7c2c3c81fd913&artist=" +
            ArtistName +
            "&album=" +
            AlbumName +
            "&format=json"
        );

        const data = await response.json();

        const numberOfTracks = data.album.tracks.track.length;
        const AlbumImage = data.album.image[2].#text;
}

Solution

  • You cannot access the #text property directly with the dot notation because it is a private field. You must use the bracket notation.

    Replace the last line of your code with

    const AlbumImage = data.album.image[2]['#text'];
    

    more details here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields

    and here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors