JSON - PHP : work BeaUtifuLLy





JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc.

  • JSON stands for JavaScript Object Notation.
  • The format was specified by Douglas Crockford.
  • It was designed for human-readable data interchange.
  • It has been extended from the JavaScript scripting language.
  • The filename extension is .json.
  • JSON Internet Media type is application/json.
  • The Uniform Type Identifier is public.json.

Uses of JSON

  • It is used while writing JavaScript based applications that includes browser extensions and websites.
  • JSON format is used for serializing and transmitting structured data over network connection.
  • It is primarily used to transmit data between a server and web applications.
  • Web services and APIs use JSON format to provide public data.
  • It can be used with modern programming languages.

Characteristics of JSON

  • JSON is easy to read and write.
  • It is a lightweight text-based interchange format.
  • JSON is language independent.

Why use JSON?

Since the JSON format is text only, it can easily be sent to and from a server, and used as a data format by any programming language.

JavaScript has a built in function to convert a string, written in JSON format, into native JavaScript objects:

JSON.parse()

So, if you receive data from a server, in JSON format, you can use it like any other JavaScript object.

JSON Syntax:

JSON syntax is derived from JavaScript object notation syntax:
  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays
Below is a simple example −

{
   "book": [
 
      {
         "language": "Java",
         "creator": "James Gosling"
      },
 
      {
         "language": "PHP",
         "creatoR": "Rasmus Lerdorf"
      }
   ]
}


JSON with PHP

Let's see how to encode and decode JSON objects using PHP programming language.

JSON Functions

PHP has some built-in functions to handle JSON.

Encoding JSON in PHP (json_encode)

PHP json_encode() function is used for encoding JSON in PHP. This function returns the JSON representation of a value on success or FALSE on failure.

Syntax:
string json_encode ( $value [, $options = 0 ] )

Parameters
value − The value being encoded. This function only works with UTF-8 encoded data.

options − This optional value is a bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG,         JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT.

Example

The following example shows how to convert an array into JSON with PHP −

php
   $myObj->course = "Rocky Jagtiani";
   $myObj->age = 39;
   $myObj->city = "Chembur";

   $Suven = json_encode($myObj);

   echo $Suven;
?>

While executing, this will produce the following result −

{"name":"Rocky Jagtiani","age":39,"city":"Chembur"}

PHP Array:
Arrays in PHP will also be converted into JSON when using the PHP function json_encode():
php
   $myArr = array("Java", "Web Technology", "Android", "Digital Marketing");

   $myJSON = json_encode($myArr);

   echo $myJSON;
?>
this will produce the following result −

["Java","Web Technology","Android","Digital Marketing"]

Decoding JSON in PHP (json_decode)
PHP json_decode() function is used for decoding JSON in PHP. This function returns the value decoded from json to appropriate PHP type.
Syntax
mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])

Paramaters
json_string − It is an encoded string which must be UTF-8 encoded data.
assoc − It is a boolean type parameter, when set to TRUE, returned objects will be converted into associative arrays.
depth − It is an integer type parameter which specifies recursion depth
options − It is an integer type bitmask of JSON decode, JSON_BIGINT_AS_STRING is supported.
Example:
The following example shows how PHP can be used to decode JSON objects −
php
   $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

   var_dump(json_decode($json));
   var_dump(json_decode($json, true));
?>
While executing, it will produce the following result −
object(stdClass)#1 (5) {
   ["a"] => int(1)
   ["b"] => int(2)
   ["c"] => int(3)
   ["d"] => int(4)
   ["e"] => int(5)
}

array(5) {
   ["a"] => int(1)
   ["b"] => int(2)
   ["c"] => int(3)
   ["d"] => int(4)
   ["e"] => int(5)
}

Error-Handling and Testing

If the JSON value could not be parsed or a nesting level deeper than the given (or default) depth is found, NULL is returned from json_decode. This means that no exception is raised by json_encode/json_deocde directly.
So how can we identify the cause of the error? The json_last_error function helps here. json_last_error returns an integer error code that can be one of the following constants (taken from here):
JSON_ERROR_NONE: No error has occurred.
JSON_ERROR_DEPTH: The maximum stack depth has been exceeded.
JSON_ERROR_STATE_MISMATCH: Invalid or malformed JSON.
JSON_ERROR_CTRL_CHAR: Control character error, possibly incorrectly encoded.
JSON_ERROR_SYNTAX: Syntax error.
JSON_ERROR_UTF8: Malformed UTF-8 characters, possibly incorrectly encoded (since PHP 5.3.3).

Want to Learn Web Technologies?

Comments

Popular posts from this blog

How E-commerce Sites can Increase Sales with Pinterest?

Every thing U can do with a Link-List + Programming_it_in_JaVa

Test Your SQL Basics - Part_1