Mailing List Archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [tlug] My first JSON object



On Sun, 04 Jul 2010 15:34:01 +0200, Fredric Fredricson
<Fredric.Fredricson@example.com> wrote:

> As far as I understand the idea behind JSON is that you send objects in 
> form of javascript code (a subset of javascript) that, when evaluated, 
> can be used as an object and dealt with appropriately.

Well, JSON *does* stand for "JavaScript Object Notation" :)

Let's say you want to create an object with a single property called
'name'. You can do it this way in JavaScript:

var myObject = { name: 'my_simple_object' };

What will happen with a server sending you JSON data back is the client
receiving the part of that, which relates purely to the data. It can then
be evaluated and incorporated into your JavaScript code.

You could therefore have something like this example.php on the server:

<?php
	$data = array( 'name' => 'my_simple_object' );
	Header("Content-Type: application/json");
	echo JSON_encode($data);
?>

When invoked, it will return the string "{name:'my_simple_object'}" as MIME
type application/json.

Once it has retrieved it, your JavaScript can parse it directly using
JavaScript's "eval" function, taking care to include it in parentheses:

var myObject = eval( '(' + json_data_received + ')' );

> I have tried this technique a couple of times and while it is probably
> very efficient it is also reputed to have some security flaws.

The above 'eval' route does indeed leave the door open for all kinds of
security issues if you cannot be 100% sure of the validity of the data
retrieved from the server. If that data is retrieved via AJAX then there's
a good chance that it *is* safe because AJAX cannot retrieve data from a
domain other than the one hosting the page invoking the AJAX request, and
that's supposed to be under your control. However, better safe than sorry,
which is why I tend to use the json2.min.js script mentioned earlier in
order to parse the JSON data in a safer manner:

var myObject = JSON.parse(json_data_received);

If there is anything other than a valid definition of an object in the data
received, then JSON.parse will halt with an error and no harm will be done.

-- 
G. Stewart - gstewart@example.com

Light travels faster than sound. That is why some people appear bright 
until you hear them speak.

Attachment: pgpGklnfkMGyz.pgp
Description: PGP signature


Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links