JSON 是字串格式,JavaScript 中操作的是**解析後的物件/陣列**。範例資料:
const jsonString = `{
"options": [
{"text": "王家灣", "value": "9"},
{"text": "李家灣", "value": "10"},
{"text": "邵家灣", "value": "13"}
]
}`;
// 必須先解析
const data = JSON.parse(jsonString).options; // 陣列 [{text, value}, ...]
for (const item of data) {
console.log(`文字:${item.text},值:${item.value}`);
}
data.forEach((item, index) => {
console.log(`${index}: ${item.text} = ${item.value}`);
});
const values = data.map(item => item.value); // ["9","10","13"]
const filtered = data.filter(item => Number(item.value) > 9); // 只保留 value > 9
const html = data.reduce((acc, item) => acc + `<option value="${item.value}">${item.text}</option>`, "");
const obj = {a: 1, b: 2};
for (const [key, value] of Object.entries(obj)) {
console.log(key, value);
}
// ❌ 錯誤:for...in 遍歷的是「鍵」(字串索引),且會包含原型鏈屬性
for (const key in data) {
console.log(key); // "0", "1", "2" (字串)
console.log(data[key]); // 正確取值,但語意不清
}
// ❌ 極度危險:任意代碼執行風險
const data = eval("(" + jsonString + ")");
// ✅ 唯一正確方式
const data = JSON.parse(jsonString);
// ❌ JSON 物件(非陣列)無 length
const jsonObj = {"options": [...]};
console.log(jsonObj.length); // undefined
// ✅ 訪問陣列屬性
console.log(jsonObj.options.length); // 3
<select id="areaSelect"></select>
<script>
fetch("/api/areas")
.then(res => res.json())
.then(json => {
const select = document.getElementById("areaSelect");
json.options.forEach(opt => {
const option = document.createElement("option");
option.value = opt.value;
option.textContent = opt.text;
select.appendChild(option);
});
})
.catch(console.error);
</script>