Working with JSON

  • Working with JSON

    JSONJavaScript Object Notation, is an open standard format that uses human-readable text to transmit data objects consisting of attribute–value pairs. It is used primarily to transmit data between a server and web application, as an alternative to XML.

    Lots of API’s return data using JSON because it is easy to unload an unnatural amount of information fairly quickly, that can be programmatic-ally searched. To see a simple example of json, lets check out reddit. For some awesome reason, reddit produces .json results for it’s pages – http://www.reddit.com/r/meme.json produces the json output for the /r/meme subreddit.
    A simplier example would be the one I found on W3 Schools:
    {“employees”:[
    {“firstName”:“John”, “lastName”:“Doe”},
    {“firstName”:“Anna”, “lastName”:“Smith”},
    {“firstName”:“Peter”, “lastName”:“Jones”}
    ]}
    Is the JSON equivalent to this XML
    <employees>
    <employee>
    <firstName>John</firstName> <lastName>Doe</lastName>
    </employee>
    <employee>
    <firstName>Anna</firstName> <lastName>Smith</lastName>
    </employee>
    <employee>
    <firstName>Peter</firstName> <lastName>Jones</lastName>
    </employee>
    </employees>

    As you can see, it is significantly shorter, making it faster for a computer to navigate, and allowing more data in total to be sent before it reaches its limit.

    If we are given the json object (obj) {“name”:”John Johnson”,”street”:”Oslo West 16″,”phone”:”555 1234567″} we can navigate the object as such (in javascript):
    obj.name
    obj.street
    obj.phone

    On the server side (php) it is slightly different, but basically the same:

    <?php
    $string = ‘{“foo”: “bar”, “cool”: “attr”}’;
    $result = json_decode($string);

    // Result: object(stdClass)#1 (2) { [“foo”]=> string(3) “bar” [“cool”]=> string(4) “attr” }
    var_dump($result);

    // Prints “bar”
    echo $result->foo;

    // Prints “attr”
    echo $result->cool;
    ?>

    It basically feels like an array, that may contain arrays within it (that gets really fun to navigate). I have some projects that use JSON responses on the server to create the dynamic pages, and I’ll try and find a copy that doesn’t have any project specific code in it that we can dig through and judge.

    mikegustafson

    Leave a comment