我创建了一个包含对象的数组,其中一些属性也是对象。我已成功将其转换为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);
}
答案 0 :(得分:1)
您可以使用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
。
答案 1 :(得分:1)
我找出原因:在将其存储在localstorage
之前,你要进行两次连字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/