What exactly is JSON?

Posted on 15. Apr, 2009 by Shawn McCool in JavaScript, Web Development

JSON is short for JavaScript Object Notation.  It’s a notation used to create JavaScript objects.

JSON looks like this:

{

name: "Shawn McCool",

language: "English"

}

When evaluated by JavaScript or decoded with another language you’d end up with an object like the one below.

person.name is equal to “Shawn McCool”

person.language is equal to “English”.

Since using JSON allows you to easily serialize arrays and objects, it’s often used during AJAX calls and web services. Below are some examples of the JavaScript Object Notation.

var myArray = ['cat', 'dog'];
var myObject = {animal: 'cow'};
alert(myArray[0]);  // outputs 'cat'
alert(myObject.animal); // outputs 'cow';

A standard set of interactions for an AJAX login script might be:

1: JavaScript client (browser) posts username and password to PHP.

$.post('/ajax.php', {
username: $('input[name=username]').val(),
password: $('input[name=password]').val()
}, function(data) {}, 'json');

2: PHP authenticates the information against the database then generates a response which is json_encoded and sent to the browser.

$user = $this->auth_model->Login($_POST['username'], $_POST['password']);

if($user)

{
$data['success'] = true;

}

else

{
$data['success'] = false;

}

echo json_encode($data);

3: JavaScript client ‘eval’uates the JSON which creates an object. JavaScript client then determines behavior based on the data in the object.

$.post('/ajax.php', {username: $('input[name=username]').val(), password: $('input[name=password]').val()}, function(data) {
if(data.success)
{
// login succeeded
} else {
// login failed
}

}, 'json');

Related Posts

  1. AJAX with jQuery: A Simple Login Example

Share this Post

Twitter Facebook MySpace Delicious Digg


Show Your Appreciation

If you'd like to express your appreciation for the work I've done why not buy me a coffee?
Click here to donate $3 to my caffeine fund.



Tags: , ,

2 Responses to “What exactly is JSON?”

  1. Justin says:

    So, how would this all work in a full AJAX transaction? Would it go something like…

    1. SQL query
    2. PHP encode to JSON
    3. JavaScript parses JSON
    4. Client sees results
    5. Client makes change to data
    6. Annnnnnd not sure from here…

  2. ShawnMcCool says:

    As AJAX example would go something like this:

    1) JavaScript client (browser) posts username and password to PHP.
    2) PHP authenticates the information against the database.
    3) PHP generates a response which is json_encoded and sent to the browser.
    4) JavaScript client ‘eval’uates the JSON which creates an object.
    5) JavaScript client then determines behavior based on the data in the object.

Leave a Reply