Results: 39
JSON is Like XML Because
- 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>
The most important keywords that can be used in this schema:
$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 used
https://www.jsonschemavalidator.net/
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 } 
It is an unordered set of
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,
}
Curly braces
{}
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"
      }

   ]
}
JSON names require double quotes. JavaScript names don't. JSON
{ "name": "John" }
In JavaScript we can have names without quotes:
{ name: "John" }
In JavaScript, keys can be strings, numbers, or identifier names:
{ 12: "John" }
In
JSON
, values must be one of the following data types:
- a string
- a number
- an object (JSON object)
- an array
- a boolean
- null
In
JavaScript
, values can be all of the above listed types, plus any other valid JavaScript expression, including:
- a function
- a date
- a symbol
- undefined
In
JSON
, string values must be written with double quotes:
{ "name":"John" }
In
JavaScript
, we can write string values with double or single quotes:
{ name: 'John' }
JSON.parse(str)
will not convert date string to date object and we get an error
let str = '{"title":"Conference","date":"2017-11-30T12:00:00.000Z"}';

let meetup = JSON.parse(str);

document.write( meetup.date.getDate() ); // Error!
The value of
meetup.date
is a string, not a
Date
object. That is why
JSON.parse
was unable to transform that string into a
Date
object. ... Passing the reviving function to
JSON.parse
as the second argument fixes the issue. The reviving function returns all values “as is”, but
date
will become a
Date
object and the error will not occur
let str = '{"title":"Conference","date":"2017-11-30T12:00:00.000Z"}';

let meetup = JSON.parse(str, function(key, value) {
  if (key == 'date') return new Date(value);
  return value;
});

alert( meetup.date.getDate() ); // now works!
The third argument of
JSON.stringify(value, replacer, space)
is the number of spaces to use for pretty formatting
let user = {
  name: "John",
  age: 25,
  roles: {
    isAdmin: false,
    isEditor: true
  }
};

document.write('<pre>' + JSON.stringify(user, null, 8) + '</pre>');
It’s fine if we want to send an object over a network. The
space
argument is used exclusively for a nice output. Note: max value of space parameter is
20
The result of the above code:
{
        "name": "John",
        "age": 25,
        "roles": {
                "isAdmin": false,
                "isEditor": true
        }
}
It has 8 spaces for each TAB
An object may provide method toJSON for to-JSON conversion. JSON.stringify automatically calls it if available
let room = {
  number: 23,
  toJSON() {
    return this.number;
  }
};

let meetup = {
  title: "Conference",
  room
};

// document.write(JSON.stringify(room));
document.write(JSON.stringify(meetup));
Result of the code above is the following
{"title":"Conference","room":23}
We can use a function instead of an array as the
replacer
let room = {
  number: 23
};

let meetup = {
  title: "Conference",
  participants: [{name: "John"}, {name: "Alice"}],
  place: room // meetup references room
};

room.occupiedBy = meetup; // room references meetup

// All the properties (except occupiedBy) are the encoded
document.write( JSON.stringify(meetup, function replacer(key, value) {
  return (key == 'occupiedBy') ? undefined : value;
}));
The function will be called for every
(key, value)
pair and should return the
replaced
value, which will be used instead of the original one. Or
undefined
if the value is to be skipped. ... In our case, we can return
value
“as is” for everything except
occupiedBy
. To ignore
occupiedBy
, the code above returns
undefined
. The result of the code above will be the following:
{"title":"Conference","participants":[{"name":"John"},{"name":"Alice"}],"place":{"number":23}}
As we expected all the values are encoded except
occupiedBy
Results: 39