×
Clear all filters including search bar
Valeri Tandilashvili's Personal Professional Blog
- Both JSON and XML are "self describing" (human readable)
- Both JSON and XML are hierarchical (values within values)
- Both JSON and XML are language independent
- Both JSON and XML can be parsed and used by lots of programming languages
- Both JSON and XML can be fetched with an XMLHttpRequest
JSON is Unlike XML Because+ JSON doesn't use end tag
+ JSON is shorter
+ JSON is quicker to read and write
+ JSON can use arrays
+ Better Performance
+ JSON can be parsed easily
+ JSON object has a type
+ All major JavaScript frameworks support JSON
+ Supported by all major JavaScript frameworks
+ Supported by most backend technologies
+ JSON is recognized natively by JavaScript (as object)
- JSON doesn't support comments
- JSON can not use attributes
- JSON offers poor extensibility as no namespace support
- Supports limited data types
JSON and XML examples
JSON (size: 52 bytes){
"company": Volkswagen,
"name": "Vento",
"price": 800000
}
XML (size: 79 bytes)<car>
<company>Volkswagen</company>
<name>Vento</name>
<price>800000</price>
</car>
Another example
JSON{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
XML<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</lastName>
</employee>
</employees>
elements
, attributes
and data types
.
Here is how XML schema looks like<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="company">
<xs:complexType>
<xs:sequence>
<xs:element name="id" type="xs:unsignedInt" />
<xs:element name="name" type="xs:string" />
<xs:element name="phone" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The XML schema is derived from the following XML:<company>
<id>2859385</id>
<name>Tanmay Patil</name>
<phone>(011) 123-4567</phone>
</company>
The XML schema is generated using the following online tool:https://www.liquid-technologies.com/online-xml-to-xsd-converter
$schema
- The $schema keyword states that this schema is written according to the draft v4 specification
title
- the title of the schema
description
- the description of the schema
type
- defines the type of the JSON (object / array)
properties
- defines various keys and their value types, minimum and maximum values to be used in JSON file
required
- this keeps a list of required properties
minimum
- minimum acceptable value for the item
exclusiveMinimum
- If "exclusiveMinimum" is present and has boolean value true, the value must be greater than the value of "minimum"
maximum
- maximum acceptable value for the item
exclusiveMaximum
- If "exclusiveMaximum" is present and has boolean value true, the value must be lower than the value of "maximum"
multipleOf
- a numeric instance is valid against "multipleOf" if the result of the division of the instance by this keyword's value is an integer
maxLength
- the length of a string instance is defined as the maximum number of its characters
minLength
- the length of a string instance is defined as the minimum number of its characters
pattern
- a string instance is considered valid if the regular expression matches the instance successfully
...
JSON schema example{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Product",
"description": "A product from Acme's catalog",
"type": "object",
"properties": {
"id": {
"description": "The unique identifier for a product",
"type": "integer"
},
"name": {
"description": "Name of the product",
"type": "string",
"minLength": 5,
"maxLength": 20
},
"price": {
"type": "number",
"minimum": 0,
"exclusiveMinimum": true
}
},
"required": [
"id",
"name",
"price"
]
}
JSON that the schema above belongs to:{
"id": 2,
"name": "Lorem ipsum dolor si",
"price": 0.5
}
If the JSON was:{
"id": 2.5,
"name": "Lorem ipsum dolor sit amet",
"price": -0.5
}
It would have the following errors:- Invalid type. Expected Integer but got Number
- String 'Lorem ipsum dolor sit amet' exceeds maximum length of 20
- Float -0.5 is less than minimum value of 0
For validating the JSON with its schema, the resource below can be usedhttps://www.jsonschemavalidator.net/
filter
, map
together.
Uses onlyMen
and underTwenty
methods for filtering the result.
Uses onlyNames
function to take only names from the objects.let people = [
{name: 'გიორგი', age: 15, gender: 'male'},
{name: 'ეკატერინე', age: 35, gender: 'female'},
{name: 'დავითი', age: 75, gender: 'male'},
{name: 'ნინო', age: 18, gender: 'female'},
{name: 'თორნიკე', age: 11, gender: 'male'}
]
function onlyMen(human) {
return human.gender == 'male'
}
function underTwenty(human) {
return human.age < 20
}
function onlyNames(human) {
return human.name
}
let onlyBoysNames = people.filter(onlyMen).filter(underTwenty).map(onlyNames)
document.write(onlyBoysNames)
string
- double-quoted Unicode{ "name":"John" }
float
- precision floating-point number{ "age":30.5 }
integer
- number without a fractional component{ "age":30 }
boolean
- true or false{ "sale":true }
array
- an ordered sequence of values{ "employees":[ "John", "Anna", "Peter" ] }
object
- an unordered collection of key:value
pairs{ "employee":{ "name":"John", "age":30, "city":"New York" } }
null
{ "middlename":null }
key/value
pairs
Each key is followed by colon :
key/value
pairs are separated by comma
The keys must be strings and should be different from each other
Objects should be used when the key
names are arbitrary strings
Objects are enclosed in curly braces {}
, it starts with {
and ends with }
{
"id": "011A",
"language": "JAVA",
"price": 500,
}
{}
hold objects
Square brackets []
hold arrays
Data is represented in key/value
pairs
Each key
is followed by colon :
key/value
pairs are separated by comma ,
Array values are separated by comma ,
...
Basic structure of JSON
{
"book": [
{
"id": "01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id": "07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
}
^
indicates the beginning of a string
&
indicates the end of a string
|
is used to represent multiple search patterns (logical OR)
[]
is used to represent any of the listed characters [abcdef]
[-]
is used to represent any characters from the range[a-g]
Select all students where last_name
contains უა
with REGEXP
operatorSELECT *
FROM students
WHERE last_name REGEXP 'უა'
Select all students where last_name
starts with გე
with REGEXP
operatorSELECT *
FROM students
WHERE last_name REGEXP '^გე'
Select all students where last_name
ends with უა
with REGEXP
operatorSELECT *
FROM students
WHERE last_name REGEXP 'უა$'
Select all students where last_name
contains უა
or ია
SELECT *
FROM students
WHERE last_name REGEXP 'უა|ია'
Select all students where last_name
contains უა
or ია
using square brackets SELECT *
FROM students
WHERE last_name REGEXP '[იუ]ა'
Select all students where last_name
ends with any one letter from the range [ა-უ]
followed by ა
using square brackets with rangeSELECT *
FROM students
WHERE last_name REGEXP '[ა-უ]ა$'
Select all students where last_name
contains ვა
or ends with ია
or starts with ცი
SELECT *
FROM students
WHERE last_name REGEXP '^ცი|ია$|ვა'
input[type=text]
, select
) value
jQuerylet value = $("#element_id").val();
JSlet value = document.getElementById('element_id').value;'
Set value 5
to the specified element (input[type=text]
, select
) value
jQuery$("#element_id").val(5);
JSlet value = document.getElementById('element_id').value = 5;'
Check if the specified checkbox is checked
jQuerylet is_checked = $("#element_id").is(":checked");
JSlet is_checked = document.getElementById('element_id').checked
Get HTML content of the specified element by element id
jQuerylet content = $("#element_id").html();
JSlet content =
document.getElementById('element_id').innerHTML
Set HTML content to the specified element by element id
jQuery$("#element_id").html('some html');
JSdocument.getElementById('element_id').innerHTML = 'some html'
Get attribute placeholder
value of the element
jQuery$('#element_id').attr('placeholder');
JSdocument.getElementById('element_id').getAttribute('placeholder');
Set attribute placeholder
value to the specified element
jQuery$('#element_id').attr('placeholder', 'new placeholder');
JSdocument.getElementById('element_id').placeholder = 'new placeholder';
Toggle class for an element
jQuery$("#element_id").toggle();
JSdocument.getElementById('element_id').classList.toggle("hide");
CSS class.hide {
display: none !important;
}
Get selected radio
value
jQuerylet result = jQuery('input:radio[name=vote]:checked').val();
JSlet result = document.querySelector('input[name=vote]:checked').value;
Find i
element inside another element with id element_id
jQuerylet icon = $("#element_id").find('i');
JSdocument.getElementById('element_id').querySelector('i');
Get data-value
attribute of datalist
element using selected text (datalist option's value
attribute)
jQuery$('#datalist_id [value="selected text"]').data('value');
JSdocument.querySelector('#datalist_id option[value="selected text"]').getAttribute('data-value')
Toggle two class for an element
jQuerylet el = $('#element')
if(el.hasClass('arrow-down')) {
el.removeClass('arrow-down');
el.addClass('arrow-up');
} else {
el.addClass('arrow-down');
el.removeClass('arrow-up');
}
JSlet el = document.getElementById('element')
if (el.classList.contains('arrow-up')) {
el.classList.remove('arrow-up');
el.classList.add('arrow-down');
} else {
el.classList.add('arrow-up');
el.classList.remove('arrow-down');
}
Ajax request
jQuery$.ajax({
url:'demo_get.asp',
success:function(sms){
$('#demo').html(sms);
}
});
JSvar xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "demo_get.asp", true);
xhttp.send();
MouseOver event
jQuery$('#element').on('mouseover', function(){
console.log('mouse over');
});
JSdocument.getElementById('element').addEventListener('mouseover', function(){
console.log('mouse over');
});
Scroll animation down to the specified element's position in 500 ms
jQuery$('html, body').animate({scrollTop:($('#element').position().top)}, 400);
JSfunction scrollDownToElement(el) {
// Milliseconds per move
let pm = 50;
// Padding from top
let mft = 150;
// Total animation milliseconds
let scroll_ms = 500;
// Calculates target element top position
let bd_pos = document.body.getBoundingClientRect();
let el_pos = document.getElementById(el).getBoundingClientRect();
let height = el_pos.top-bd_pos.top-mft;
// Calculates per move px
let spm = height / (scroll_ms / pm);
// The animation counter to stop
let spmc = 1;
let scroll_timer = setInterval(function() {
// Moves down by {spm} px
window.scrollBy(0, spm);
spmc++;
// Stops the animation after enough iterations
if (spmc > (scroll_ms / pm)) {
clearInterval(scroll_timer);
}
}, pm);
}
scrollDownToElement('element');
200 OK
- Standard response for successful HTTP requests
201 Created
- The request has been fulfilled, resulting in the creation of a new resource
204 No Content
- The server successfully processed the request and is not returning any content
304 Not Modified
- Indicates that the resource has not been modified since the version specified by the request headers If-Modified-Since or If-None-Match
400 Bad Request
- The server cannot or will not process the request due to an apparent client error (e.g., malformed request syntax, too large size, invalid request message framing, or deceptive request routing)
401 Unauthorized
- Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource
403 Forbidden
- The request was a valid request, but the server is refusing to respond to it. The user might be logged in but does not have the necessary permissions for the resource
404 Not Found
- The requested resource could not be found but may be available in the future. Subsequent requests by the client are permissible
409 Conflict
- Indicates that the request could not be processed because of conflict in the request, such as an edit conflict between multiple simultaneous updates
500 Internal Server Error
- A generic error message, given when an unexpected condition was encountered and no more specific message is suitable