JSON Example.

Lunch and Learn Example 1

by Rozina Szogyenyi

HTML

<span id="peepsContent">Peeps is now an object...<br /></span>

<br/>
<br/>
<div id="peepsFriendly"></div>Once you have established your object, you may access it's properties via ".propertyname".
<br />
<br /><b>Example:</b> 
<br />Because I know from the jSON that Ellis is the second object in the array (and that javascript arrays are zero based), I can access that object's properties by the index number and dot-notation.
<br />
<pre>var thatGuy = peeps.People[1].Name;</pre>

<br />
<b>That Guy </b> : <span id="ellis"></span>

<br />
<br /> <b>Other things to note</b>
Generally you'll get json as a string from a web service or other...so you'd need to call something like:
<br />
<pre>var peeps = JSON.parse(yourjsonstring); </pre>
....which creates the actual object from the string.
<br />
<br />...additionally, you can convert this object back to a string to repackage for posting or... whatever by using:
<pre>var somestring = JSON.stringify(peeps);</pre>

JavaScript

var d = document;

//here's your json being referenced as an object directly (because curly braces and no quotes).

var peeps = {
    "People": [{
        "Name": "Brad Larsen",
            "Title": "Some Guy",
            "Email": "[email protected]"
    }, {
        "Name": "Ellis Roakes",
            "Title": "Guy who gets lots of haircuts",
            "Email": "[email protected]"
    }, {
        "Name": "Jeremy Lindapotato",
            "Title": "Bearded Allergy Guy",
            "Email": "[email protected]"
    }]
};

//look ...no jQuery... (This just proves that peeps is an object btw).
d.querySelector("#peepsContent").innerHTML += peeps;


//This is a callback... 
function prettyNames(p, index, array) {
    d.querySelector("#peepsFriendly").innerHTML += "<b>" + p.Name + "</b><br/>" + p.Title + "<br />" + p.Email + "<br /><br />";
}

//This is one way of iterating through an array.  It was introduced in ES5, but is just gaining traction
//now that we're talking about ES6.
peeps.People.forEach(prettyNames);

//just so you can tell where the last array ends.
d.querySelector("#peepsFriendly").innerHTML += "<hr />The other array example<br/><br/>";
//Here's a more familiar way of doing the same thing.
for (var i = 0; i < peeps.People.length; i++) {
    var p = peeps.People[i];
    d.querySelector("#peepsFriendly").innerHTML += "<b>" + p.Name + "</b><br/>" + p.Title + "<br />" + p.Email + "<br /><br />";
}


//Read the "Example" to see what I'm doing here.... 
var thatGuy = peeps.People[1].Name;
d.querySelector("#ellis").innerHTML = thatGuy;