Working with JSON for Web Development

This chapter will help you to learn JSON fundamentals, example, syntax, array, object, encode, decode, file, date and date format. You will also be able to learn JSON examples with other technologies such as Java and PHP.

JSON with PHP


PHP allows us to encode and decode JSON by the help of json_encode() and json_decode functions.


JSON Functions

Function Libraries
json_encode Returns the JSON representation of a value.
json_decode Decodes a JSON string.
json_last_error Returns the last error occurred.

PHP json_encode

The json_encode() function returns the JSON representation of a value. In other words, it converts PHP variable (containing array) into JSON.

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>

<?php
$arr2 = array('firstName' => 'Rahul', 'lastName' => 'Kumar', 'email' => 'rahul@gmail.com');
echo json_encode($arr2);
?>

PHP json_decode

The json_decode() function decodes the JSON string. In other words, it converts JSON string into a PHP variable.

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.

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json, true));//true means returned object will be converted into associative array
?>

Output:

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


<?php
$json2 = '{"firstName" : "Rahul", "lastName" : "Kumar", "email" : "rahul@gmail.com"}';
var_dump(json_decode($json2, true)); ?>

Output:

array(3) {
["firstName"]=> string(5) "Rahul"
["lastName"]=> string(5) "Kumar"
["email"]=> string(15) "rahul@gmail.com"
}