JSON Object Example
{
"employee": {
"name": "sonoo",
"salary": 56000,
"married": true
}
}
JSON Array example
example of JSON array having values.
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
[
{"name":"Ram", "email":"Ram@gmail.com"},
{"name":"Bob", "email":"bob32@gmail.com"}
]
JSON Nested Object Example
{
"firstName": "Sonoo",
"lastName": "Jaiswal",
"age": 27,
"address" : {
"streetAddress": "Plot-6, Mohan Nagar",
"city": "Ghaziabad",
"state": "UP",
"postalCode": "201007"
}
}
JSON Array of Strings
Let's see an example of JSON arrays storing string values.
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
JSON Array of Numbers
Let's see an example of JSON arrays storing number values.
[12, 34, 56, 43, 95]
JSON Array of Objects
Let's see a simple JSON array example having 4 objects.
{"employees":[
{"name":"Ram", "email":"ram@gmail.com", "age":23},
{"name":"Shyam", "email":"shyam23@gmail.com", "age":28},
{"name":"John", "email":"john@gmail.com", "age":33},
{"name":"Bob", "email":"bob32@gmail.com", "age":41}
]}
PHP json_encode example 1
Let's see the example to encode JSON.
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Output
{"a":1,"b":2,"c":3,"d":4,"e":5}
PHP json_encode example 2
Let's see the example to encode JSON.
<?php
$arr2 = array('firstName' => 'Rahul', 'lastName' => 'Kumar', 'email' => 'rahul@gmail.com');
echo json_encode($arr2);
?>
Output
{"firstName":"Rahul","lastName":"Kumar","email":"rahul@gmail.com"}
PHP json_decode
<?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 json_decode example 2
Let's see the example to decode JSON string.
<?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"
}
Top comments (0)