I have come up with 4 ways to access the contents of a JSON object.
Are there any other ways available?
Would a JSON.stringify or JSON.parse approach be better?
Should I avoid the use of the eval() technique completely?
Here is my code:
[code]
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″ />
<title> JSON Object Reference </title>
<style>
fieldset { width: 20%; float: left; }
#fs1 { background-color: pink; }
#fs2 { background-color: lime; }
#fs3 { background-color: yellow; }
#fs4 { background-color: orange; }
</style>
</head>
<body>
<fieldset> <legend>Rolls (Direct access)</legend> <pre id=”fs1″></pre> </fieldset>
<fieldset> <legend>Rolls (Access via function)</legend> <pre id=”fs2″></pre> </fieldset>
<fieldset> <legend>Rolls (Access via array)</legend> <pre id=”fs3″></pre> </fieldset>
<fieldset> <legend>Rolls (Access via eval)</legend> <pre id=”fs4″></pre> </fieldset>
<script>
function doc(IDS) { return document.getElementById(IDS); }
Rolls = {
FRR33:’0:FRR33 3 2 1 5 1 2 3 1′, // FRR33
FRR43:’0:FRR43 4 2 1 5 1 2 3 1′, // FRR43
FRR44:’0:FRR44 4 2 1 5 1 2 4 1′, // FRR44
FR33: ‘0:FR33 3 2 1 3 2 1 5 1’, // FR33
FR34: ‘0:FR34 3 2 1 4 2 1 5 1’, // FR34
FR44: ‘0:FR44 4 2 1 4 2 1 5 1’ // FR44
};
/* ——————–Direct Access————————————- */
doc(‘fs1′).innerHTML += Rolls.FRR33+’n’;
doc(‘fs1′).innerHTML += Rolls.FRR43+’n’;
doc(‘fs1′).innerHTML += Rolls.FRR44+’n’;
doc(‘fs1′).innerHTML += Rolls.FR33+’n’;
doc(‘fs1′).innerHTML += Rolls.FR34+’n’;
doc(‘fs1′).innerHTML += Rolls.FR44+’n’;
/* ——————–Access via function——————————- */
function getObj(info) { return info; } // Rolls.info;
doc(‘fs2′).innerHTML += getObj(Rolls.FRR33)+’n’;
doc(‘fs2′).innerHTML += getObj(Rolls.FRR43)+’n’;
doc(‘fs2′).innerHTML += getObj(Rolls.FRR44)+’n’;
doc(‘fs2′).innerHTML += getObj(Rolls.FR33)+’n’;
doc(‘fs2′).innerHTML += getObj(Rolls.FR34)+’n’;
doc(‘fs2′).innerHTML += getObj(Rolls.FR44)+’n’;
/* ——————–Access via array———-(similar to above)—— */
var seqObj = [Rolls.FRR33, Rolls.FRR43, Rolls.FRR44, Rolls.FR33, Rolls.FR34, Rolls.FR44];
for (var i=0; i<seqObj.length; i++) {
doc(‘fs3′).innerHTML += getObj(seqObj[i])+’n’;
}
/* ——————–Access via eval———————————– */
function getRoll(info) { return eval(‘Rolls.’+info); }
var seqVar = [‘FRR33’, ‘FRR43’, ‘FRR44’, ‘FR33’, ‘FR34’, ‘FR44’ ];
for (var i=0; i<seqVar.length; i++) {
doc(‘fs4′).innerHTML += getRoll(seqVar[i])+’n’;
}
/* ——————–Alternative methods???—————————- */
</script>
</body>
</html>