JSON and REST

home

Part 1. json: javascript demo code
// javascript object
var jsObject = { dog_name: "Tairo", dog_color: "brown" };
alert("in javascript object, dog_name = " + jsObject.dog_name);

// json object
var jsonObject = { "dog_name": "Tairo", "dog_color": "brown" };
alert("in jsonObject " + jsonObject["dog_name"]);

/*
    **********  in javascript, java object vs json in string
    1. When you use use javascript, web client, or nodejs, you can use json object.
    2. When you move data into web, json in string is required.
    3. PHP server code, and other languages, swift, java, have to communicated with the text.
    4. Each other langauges have their ways to do the conversions during state changes.
    5. W3C has a tutorial for JSON.
*/

// json object in string
var strJSON = '{ "dog_name": "Tairo", "dog_color": "brown" }';
alert("json object in string " + strJSON);

// convert json object to string
var strJSON2 = JSON.stringify(jsonObject);
alert("json object in string using JSON.stringify method " + strJSON2);

// convert string to javascript object in JSON notation
var jsonObject2 = JSON.parse(strJSON);
alert("using JSON.parse method to convert string to javascript object   " + jsonObject2);
alert("java object in JSON notation " + JSON.stringify(jsonObject2));   


Part 2. REST

2.1 overall rest picture using json

rest

2.2 demo

        // add a new php file,  3s_phpRest.php, inside php tags, add two lines
        // simulate data from database
// $result = mysqli_query($conn, $sql); // $arr = array(); // while($row =mysqli_fetch_assoc($result)) // { // array_push($arr, $row); // } // echo json_encode($arr); // php array ==> string in json $data = '[{"dog_name":"Tairo","dog_color":"brown"},{"dog_name":"Emi","dog_color":"white"}]'; echo $data;