JS:不能抓取json键



我正在提交一个JSON并试图访问单个键。

在此期间,我已经用不同的方法尝试过了。

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为什么。我不需要解析json。每个代码解释都是这样做的,就像我的一个变体。

//编辑

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":[]}]}

仍然没有访问

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

//解决方案//双解析LMAO

听起来你没有解析数据-我猜jsonData实际上是一个字符串的结果。您需要使用JSON。解析将字符串转换为对象。

试题:

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

. .看看你能得到什么。

最新更新