[英]JSON.parse() returning strings
我正在嘗試遍歷對象數組並使用其值是每個 object 的全部內容的選項填充 HTML select 元素。 填充成功,但是對象在這個過程中變成了字符串,我不知道如何將它們變成對象。
Running them through JSON.parse() gives me "Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse." 我的研究表明,當您在已經是 object 的東西上使用 JSON.parse() 時會發生這種情況,但事先在數據上運行 typeOf() 會發現它是一個字符串。
如果我改為通過 JSON.parse(JSON.stringify(data)) 運行數據,我不會收到此錯誤,但它的 output 仍然是一個字符串。
請幫助我理解我對 JSON.parse() 的誤解。 謝謝你。
const selectors = document.getElementsByClassName("ingredientSelector");
const cookButton = document.getElementById("cookButton");
//very large array of ingredient objects
let selectorOptions = "<option value = 'Nothing'>Nothing</option>";
for (let i = 0; i < ingredients.length; i++){
selectorOptions += ("<option value = '" + ingredients[i] + "'>" + ingredients[i].name + "</option>");
}
Array.prototype.forEach.call(selectors,function(selector){
selector.innerHTML = selectorOptions;
});
function cook(ingredients){
console.log("Cooking with ingredients: " + ingredients);
}
cookButton.addEventListener("click", function(){
let ingredients = [];
Array.prototype.forEach.call(selectors,function(selector){
if(selector.value !== 'Nothing'){
console.log(typeof(selector.value))
JSON.parse(selector.value);
let JSONString = JSON.stringify(selector.value);
console.log(typeof(JSONString));
let JSONObject = (JSON.parse(JSONString));
console.log(typeof(JSONObject));
console.log(JSONObject.name);
}
console.log(ingredients);
cook(ingredients);
});
});
問題是您如何為要插入每個選擇器的option
構建value
屬性。 在這條線上:
selectorOptions += ("<option value = '" + ingredients[i] + "'>" + ingredients[i].name + "</option>");
您的評論說ingredients
是對象數組,因此ingredients[i]
將是 object。 默認情況下,將object 連接到字符串會將其轉換為[object Object]
- 這就是導致錯誤的原因。 您最終會得到一個看起來像這樣的選項,也許:
<option value = '[object Object]'>Raw Prime Meat<object>
這里有兩種完全有效的方法。 您可以將成分索引存儲在選項值中,然后您可以使用它稍后從主數組中查找成分,或者您應該使用JSON.stringify(ingredients[i])
將 object 轉換為JSON.parse
使您的代碼按原樣工作的字符串。
所以這可以正常工作:
selectorOptions += ("<option value = '" + JSON.stringify(ingredients[i]) + "'>" + ingredients[i].name + "</option>");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.