Specializations

Friday, March 29, 2013

JSON vs. Arrays


What is JSON

  • JSON = JavaScript Object Notation
  • Object that contains Data
  • Better than XML for use with Javascript (cause it is not a markup language and it is lightweight)
  • Easier and quicker to setup than XML on the server-side

JSON vs. Arrays

  • JSON wins
  • Not a good comparison since JSON can have arrays inside of it
  • JSON can store nested objects and arrays, it is much more powerful than an array

What does JSON look like?

Declaring an empty JSON object in Javascript:
var data = {};
A basic JSON object:
var data = {kind: "Human", water: "Clear Blue", help: false};
A complex JSON object:
var bar = {prop: [{key: "Value", x: "yes"},{alien: false, skin: "Green Tone"}], sand:true};
var data = {kind: "Human", water: "Clear Blue", help: false, extra: bar};

How do I set it up a JSON in PHP?

A simple example that outputs a static JSON object:
<?
header("Content-type: application/json");
echo '{"items: [ key: "value", another_key: { k: "val", x: "yes" } ]}';
?>
Convert PHP arrays into JSON:
<?
header("Content-type: application/json");
$my_object '{"items: [ key: "value", another_key: { k: "val", x: "yes" } ]}';
$count = 2;
echo json_encode(array("items" => $my_object"count" => $count));
?>
Get data from a database and turn it into JSON with PHP:
<?
$input $_GET["q"];
$data array();
// query your DataBase here looking for a match to $input
$query = mysql_query("SELECT * FROM my_table WHERE my_field LIKE '%$input%'");
while ($row = mysql_fetch_assoc($query)) {
$json array();
$json['value'] = $row['id'];
$json['name'] = $row['username'];
$json['image'] = $row['user_photo'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>

Using JSON with jQuery

Query the server and alert some JSON data:
$.getJSON("http://mysite.com/path/to/script"function(data){
var items = data.items[0];
alert(items.key);
});

No comments:

Post a Comment