×
Clear all filters including search bar
Valeri Tandilashvili's JSON Notes
JSON schema
is a JSON document that describes other JSON document. It is a specification for JSON based format to define the structure of JSON data- Describes your existing data format
- Defines the structure of a JSON message
- Clear, human- and machine-readable documentation
- Complete structural validation, useful for automated testing
- Complete structural validation, validating JSON message
- Can be used to validate API request and response
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
// Returns the JSON representation of a value (pretty printed)
echo json_encode($arr, JSON_PRETTY_PRINT);
Result of the above code{
"a": 1,
"b": 2,
"c": 3,
"d": 4,
"e": 5
}
The following example shows how the PHP objects can be converted into JSONclass Emp {
public $name = "";
public $hobbies = [];
public $birthdate = "";
}
$e = new Emp();
$e->name = "sachin";
$e->hobbies = ["sport", "reading"];
$e->birthdate = date('Y-m-d', strtotime('2015-11-18'));
echo json_encode($e);
The above code will produce the following result{"name":"sachin","hobbies":["sport","reading"],"birthdate":"2015-11-18"}
Decoding JSON in PHP (json_decode)
The following example shows how PHP can be used to decode JSON objects$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
// Decoding into an object
var_dump(json_decode($json));
// Decoding into an array
var_dump(json_decode($json, true));
While executing, it will produce the following resultobject(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)
}
var text = '{ "name":"John", "age":"function () {return 30;}", "city":"New York"}';
var obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age();
var text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
var obj = JSON.parse(text);
obj.birth = new Date(obj.birth);
document.write(obj.name + ", " + obj.birth)
Also we can use the second parameter of the JSON.parse()
function, called reviver
that checks each property, before returning the valuevar text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';
var obj = JSON.parse(text, function (key, value) {
if (key == "birth") {
return new Date(value);
} else {
return value;
}
});
document.write(obj.name + ", " + obj.birth)
JSONP
is a technique to get data from server without cross-domain issues.
JSONP does not use the XMLHttpRequest
, instead it uses <script>
tag.
window.onload = function() {
var s = document.createElement("script");
s.src = "https://www.w3schools.com/js/demo_jsonp.php";
document.write(s.outerHTML);
};
// This function will run after the content is fully loaded from the server
function myFunc(myObj) {
document.write(myObj.name + " is " + myObj.age + " and he lives in " + myObj.city);
}
Requesting a content from another domain can cause problems, due to cross-domain policy. <script>
tag does not have this problem and that is the reason why it uses the tag instead of using XMLHttpRequest
object.
...
Content of the remote demo_jsonp.php
filemyFunc({"name":"John", "age":30, "city":"New York"});
callback function
name is the same as the callback
variable passed to the URL
https://api.github.com/users/yui?callback=handleJSONP_variable
The content returned from the request:handleJSONP_variable({"meta": {
"Content-Type": "application/javascript; charset=utf-8",
"Cache-Control": "public, max-age=60, s-maxage=60",
"Vary": "Accept",
"status": 200,
...
}, "data": {
"login": "yui",
"name": "YUI Library",
"company": null,
"blog": "http://yuilibrary.com/",
"location": "Sunnyvale, CA",
"email": null,
"public_repos": 31,
...
}})
string
, number
, object
, array
, boolean
or null
...
In JavaScript:
Array values can be all of the above, plus any other valid JavaScript expression, including functions
, dates
, undefined
, symbol
comment
inside the object as a property
{
"employee": {
"name": "George",
"a0ge": "30",
"city": "Tbilisi",
"comments": "The best student ever"
}
}
var myObj = {
"name":"John",
"age":30,
"cars": {
"car1":"Ford",
"car2":"BMW",
"car3":"Fiat"
}
}
// Accessing nested object properties
document.write(myObj.cars.car2);
document.write("<br />");
document.write(myObj.cars["car2"]);
document.write("<br />");
document.write(myObj["cars"]["car2"]);
<select>
element using document.createElement
method and fills with JSON arrayoptionArray = [
"daily",
"weekly",
"biweekly",
"monthly"
];
// Creates <select> element
let selector = document.createElement('select');
for(let option in optionArray) {
let value = optionArray[option];
// Creates <option> element for <select>
let newOption = document.createElement("option");
newOption.value = value;
newOption.innerHTML = value;
selector.options.add(newOption);
}
// Adds the <select> element into the document object
document.body.appendChild(selector);