Skip to content

Instantly share code, notes, and snippets.

@lamprosg
Created March 3, 2013 12:00
Show Gist options
  • Select an option

  • Save lamprosg/5075850 to your computer and use it in GitHub Desktop.

Select an option

Save lamprosg/5075850 to your computer and use it in GitHub Desktop.
Intro to JSON
//WHAT IT LOOKS LIKE
//Javascript and json objects are written inside "{ }"
var bar = { name: "foo" , city: "SanDiego" };
var data = { sand: true , water:"Clear" , extra: bar }; //bar is the above object
/*******************************************/
//Getting the data from json
var watervale = data.water; //watervalue = "clear"
var namevalue = data.extra.name; //namevalye = "foo"
/*****************************************************************************************/
/*****************************************************************************************/
//This contains objects with an array of multiple objects inside
//props[0] props[1]
var bar = { props: [{foo:"bar" , kind:"beach"} , {me:"you" , flag:true }] , help: false };
var data = { sand: true , water:"Clear" , extra: bar };
/*******************************************/
//Getting the data
var x = data.extra.props[0]; //x = {foo:"bar" , kind:"beach"}
alert(x.kind); //alert "beach"
//Changing the value in javascript would be
x.kind = "anothervalue";
//NOTE: keys can also be in ""
//Returning data from your database in JSON
//You need to add this to the script that will be called (ex.using AJAX) to get you the data
header("Content-type: application/json");
//example
$my_obj = '{ items:[key1:"value1", {key2:"value2" , key3:"value3"}], help:false }';
$count = 2;
//Convert any array to JSON format
echo json_encode(array("items" => $my_obj , "count" => $count));
//The above will output
{ items: $my_oj , count:2 }
//Get data
//funtion is the callback funtion when the data are available
//data is the object returned
$.getJSON("the_URL_of_the_scipt.php" , funtion(data){
var item = data.items[0];
alert(item.key);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment