[英]Parse JSON into Object Array
我創建了一個包含對象的數組,其中一些屬性也是對象。 我已經成功將其轉換為JSON,並且需要將其轉換回對象數組,或者以某種方式從JSON對象的正確索引中提取正確的數據。
更新
這是我通過JSON.parse運行它時得到的示例:
[{"Result":"Fail","Method":"T97E-v1","Beam1":{"BeamAge":"1","WidthUpper":1,"WidthCenter":1,"WidthLower":1,"WidthAverage":1,"DepthRight":1,"DepthCenter":1,"DepthLeft":1,"DepthAverage":1,"MaxLoad":1,"FS":18,"PSI":"18.00000","BreakOutside":"No"},"Beam2":{"BeamAge":"","WidthUpper":null,"WidthCenter":null,"WidthLower":null,"WidthAverage":null,"DepthRight":null,"DepthCenter":null,"DepthLeft":null,"DepthAverage":null,"MaxLoad":null,"FS":null,"PSI":"NaN"},"WaitForCuring":"No","AverageOfBeams":"NaN"}]
更新2
這是關於我在做什么的代碼:
try {
localStorage["flexuralStrengthSamples"] = JSON.stringify(JSON.stringify(t97Samples));
var parsedObject = JSON.parse(localStorage["flexuralStrengthSamples"]);
console.log(parsedObject);
console.log(parsedObject[0].Beam1.MaxLoad);
} catch (err) {
alert(err.message);
}
您可以使用JSON.parse()
解析JSON。
更新
這是JSON.parse()
中的數據樣本。
[{"Result":"Fail","Method":"T97E-v1","Beam1":{"BeamAge":"1","WidthUpper":1,"WidthCenter":1,"WidthLower":1,"WidthAverage":1,"DepthRight":1,"DepthCenter":1,"DepthLeft":1,"DepthAverage":1,"MaxLoad":1,"FS":18,"PSI":"18.00000","BreakOutside":"No"}}]
為了獲取數據,您需要對數組使用括號符號,對對象使用點符號。 因此,讓data
等於該JSON數組,則可以執行data[0].Result
(即"Fail"
)或data[0].Beam1.MaxLoad
(即1
。
我知道原因:在將其存儲在本地存儲中之前,您要進行兩次穿線
try {
localStorage["flexuralStrengthSamples"] = (JSON.stringify(t97Samples)); //Stringify only once, since localstorage values needs to be string
var parsedObject = JSON.parse(localStorage["flexuralStrengthSamples"]); // should give the original object.
console.log(parsedObject[0].Beam1.MaxLoad); // Since parsedObject is still string, this was failing. Now should work fine
} catch (err) {
alert(err.message);
}
在這里查看工作的小提琴: http : //jsfiddle.net/sandenay/pnb88p4s/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.