Belajar JSON

Bagi sebagian orang Javacript merupakan metode web masa depan dan kenyataannya dari hari ke hari anggapan itu semakin nyata. JSON merupakan cara tebaik untuk menyimpan data ketika kita menggunakan Javascript. Tidak diragukan lagi.

Tulisan ini sekadar membantu mengawali belajar JSON dan harapannya bisa memudahkan kita untuk memahmi konsep di balik JSON itu. Dari sini, insyaAllah kita bisa mudah memahami tutorial-tutorial tentang JSON yang lebih rumit. Selamat membaca!

Apa dan siapa 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);
});
Pos ini dipublikasikan di Developer dan tag . Tandai permalink.

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s