I have created an array that contains objects, some of the properties are also objects. I have converted it to JSON successfully and need to convert it back into an array of the objects, or somehow pull the correct data from the correct index of the JSON object.
Update
This is a sample of what I get when I run it through 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"}]
Update 2
Here is the code around what I'm doing:
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);
}
2 Answers 2
I figured out the reason: You are stringyfying twice before storing it in 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);
}
See the working fiddle here: http://jsfiddle.net/sandenay/pnb88p4s/
Comments
You can parse JSON using JSON.parse().
Update
Here is a sample of your data from 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"}}]
In order to get at your data, you need to use bracket-notation for arrays and dot-notation for objects. So, let data be equal to that JSON Array, then you can do data[0].Result, which is "Fail", or data[0].Beam1.MaxLoad, which is 1.
3 Comments
data[0].Beam1.MaxLoad prints 1 in the console for me
stringifytwice? one is enough. Also simple logic: if you twice convert to string, so and parse you also should twice. But anyway, enough callstringifyonce