TheCallofDuty
TheCallofDuty

Reputation: 153

JS: Cant grab json key

I am submitting a JSON and trying to access the individual keys.

I have tried it in different ways in the meantime.

    const jsonData = target.getAttribute('datas');
    console.log(jsonData.id); // returns undefined

    const jsonData = target.getAttribute('datas');
    console.log(jsonData[0].id); // returns undefined

    for(let key of Object.keys(jsonData)) {
        console.log(key);
    } // returns every single letter

    for (const [key, value] of Object.entries(jsonData)) {
        console.log(`${key}: ${value}`);
    } // returns every single letter

idk why. i dont need to parse the json. Every code explain do it same like one variant of mine.

// EDIT

The JSON:

{"id":"adf6cfce022e4798b11f3ae6bcd8dc0f","manufacturer":"..ö..","productName":"Blue Boat XL","productNumber":"A80801902","worth":[{"currencyId":"b7d2554b0ce847cd82f3ac9bd1c0dfca","net":11.05,"gross":11.9,"linked":false,"listPrice":null,"percentage":null,"regulationPrice":null,"extensions":[]}]}

still no access

const jsonData = JSON.parse(target.getAttribute('datas'));
    console.log(jsonData.id);

// THE SOLUTION // double parse LMAO

Upvotes: 0

Views: 39

Answers (1)

Ben Clayton
Ben Clayton

Reputation: 82219

sounds like you haven't parsed the data - I'm guessing jsonData is actually a string as a result. You need to use JSON.parse to convert the string into an object.

try:

const jsonData = JSON.parse(target.getAttribute('datas'));
console.log(jsonData);

.. and see what you get.

Upvotes: 2

Related Questions