What is JSON? with example (PHP with JSON)

What is JSON?

JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.

Key and value : The two primary parts that make up JSON are keys and values. Together they make a key/value pair.
  • Key: A key is always a string enclosed in quotation marks.
  • Value: A value can be a string, number, boolean expression, array, or object.
  • Key/Value Pair: A key value pair follows a specific syntax, with the key followed by a colon followed by the value. Key/value pairs are comma separated.


Type of values:
  • Array: An associative array of values.
  • Boolean: True or false.
  • Number: An integer.
  • Object: An associative array of key/value pairs.
  • String: Several plain text characters which usually form a word.

Example : Ok let's start php+mysql with json
create database = json_demo

create table =
CREATE TABLE MyGuests (

id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,

firstname VARCHAR(30) NOT NULL,

lastname VARCHAR(30) NOT NULL,

email VARCHAR(50),

reg_date TIMESTAMP

)

insert some record in table

create index.php (before run this script check your folder permission)
    <?php
         //database connect
         $con = mysql_connect("localhost","root","");
       
         //database select
         $db = mysql_select_db("json_demo");
       
       
         $sel = "select * from MyGuests";
         $qry = mysql_query($sel);
       
         $var = array();
       
         while($row = mysql_fetch_assoc($qry))
         {
            $var[] = $row;
         }
       
         echo $json = '{"MyGuests":'.json_encode($var).'}';
           
            $fp = fopen('MyGuests.json', 'w+');
            fwrite($fp,$json);
            fclose($fp);
           
        ?>

Check json file in directory

Format json code here http://pro.jsonlint.com/

You will look like this
    {
            "MyGuests": [
                {
                    "id": "1",
                    "firstname": "kishan",
                    "lastname": "sanghani",
                    "email": "kishan.sanghani@hotmail.com",
                    "reg_date": "2015-11-23 15:02:53"
                },
                {
                    "id": "2",
                    "firstname": "amit",
                    "lastname": "sanghani",
                    "email": "amit.sanghani@gmail.com",
                    "reg_date": "2015-11-23 15:03:24"
                }
            ]
        }

2 comments:

  1. very nice tutorial it will help me to how to create json file

    ReplyDelete

Powered by Blogger.