Javascript 迭代JSON数据并将字段文本附加到div(ES6)
我正在使用fetch:Javascript 迭代JSON数据并将字段文本附加到div(ES6),javascript,json,ecmascript-6,fetch,Javascript,Json,Ecmascript 6,Fetch,我正在使用fetch: fetch('https://www.website.com/wp-json/acf/v3/options/options') .then(function(response) { return response.json(); }) .then(function(myJson) { console.log(JSON.stringify(myJson)); }); }); 如何使用ES6获取数据字段及其文本内容
fetch('https://www.website.com/wp-json/acf/v3/options/options')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
});
如何使用ES6获取数据字段及其文本内容;并附加到
示例数据/JSON响应:
..'1yr_short_copy":"<p>Our 1 Year Money Back Guarantee either leaves you'..
。'1yr\u short\u copy:“我们的1年退款保证要么离开您”。。
实际上,我正在寻找使用fetch和ES6(非jQuery)实现这一点的最佳方法
期望输出:
我们的1年退款保证要么让您
您的JSON首先在response.JSON
中解析为对象
,然后使用JSON.stringify(myJson)
将其转换回JSON,这使得它无法使用。不要那样做。只需使用已解析的对象
来更新
的文本内容
值
由于您的1yr\u short\u copy
属性以数字开头,因此只能使用括号而不是点符号来选择它。避免使用数字命名对象中关键点的第一个字符
fetch('https://www.website.com/wp-json/acf/v3/options/options')
.then(function(response) {
return response.json();
})
.then(function(obj) {
const paragraph = document.getElementById('id');
if (paragraph !== null && obj.hasOwnProperty('1yr_short_copy') { // Check if element is found and your 1yr_short_copy key exists.
paragraph.textContent = obj['1yr_short_copy']; // Brackets notation
}
});
});
那么JSON中是什么呢?目前还不清楚读取对象有什么困难。也许共享一个示例输出会有所帮助。正如埃帕斯卡雷洛所指出的,你想做什么并不十分清楚,因此,你问什么也不十分清楚。您的“数据字段”是什么?在哪里
fetch('https://www.website.com/wp-json/acf/v3/options/options')
.then(function(response) {
return response.json();
})
.then(function(obj) {
const paragraph = document.getElementById('id');
if (paragraph !== null && obj.hasOwnProperty('1yr_short_copy') { // Check if element is found and your 1yr_short_copy key exists.
paragraph.textContent = obj['1yr_short_copy']; // Brackets notation
}
});
});