Friday, October 13, 2017

JSON HTML

JSON HTML

JSON can be easily translated into JavaScript. JavaScript can be used to make HTML in your web pages.

HTML Table

Make an HTML table with data received as JSON:

Example

obj = { "table":"customers""limit":20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        txt += "<table border='1'>"
        for (x in myObj) {
            txt += "<tr><td>" + myObj[x].name + "</td></tr>";
        }
        txt += "</table>" 
        document.getElementById("demo").innerHTML = txt;
    }
}
xmlhttp.open("POST""json_demo_db_post.php"true);
xmlhttp.setRequestHeader("Content-type""application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
HTML Drop Down List

Make an HTML drop down list with data received as JSON:

Example

obj = { "table":"customers""limit":20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        txt += "<select>"
        for (x in myObj) {
            txt += "<option>" + myObj[x].name;
        }
        txt += "</select>" 
        document.getElementById("demo").innerHTML = txt;
    }
}
xmlhttp.open("POST""json_demo_db_post.php"true);
xmlhttp.setRequestHeader("Content-type""application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
Free online tool to format, edit, and validate JSON: JSON Formatter tool.

Thursday, June 1, 2017

JSON Shortcuts - Line Operations and Selection

Find out basic keyboard shortcuts of JSON for line operations and selection action through the list below.

JSON shortcuts

JSON Shortcuts - Line Operations

Windows/LinuxMacAction
Ctrl-DCommand-DRemove line
Alt-Shift-DownCommand-Option-DownCopy lines down
Alt-Shift-UpCommand-Option-UpCopy lines up
Alt-DownOption-DownMove lines down
Alt-UpOption-UpMove lines up
Alt-DeleteCtrl-KRemove to line end
Alt-BackspaceCommand-BackspaceRemove to linestart
Ctrl-BackspaceOption-Backspace, Ctrl-Option-BackspaceRemove word left
Ctrl-DeleteOption-DeleteRemove word right
---Ctrl-OSplit line

JSON Shortcuts - Selection

Windows/LinuxMacAction
Ctrl-ACommand-ASelect all
Shift-LeftShift-LeftSelect left
Shift-RightShift-RightSelect right
Ctrl-Shift-LeftOption-Shift-LeftSelect word left
Ctrl-Shift-RightOption-Shift-RightSelect word right
Shift-HomeShift-HomeSelect line start
Shift-EndShift-EndSelect line end
Alt-Shift-RightCommand-Shift-RightSelect to line end
Alt-Shift-LeftCommand-Shift-LeftSelect to line start
Shift-UpShift-UpSelect up
Shift-DownShift-DownSelect down
Shift-PageUpShift-PageUpSelect page up
Shift-PageDownShift-PageDownSelect page down
Ctrl-Shift-HomeCommand-Shift-UpSelect to start
Ctrl-Shift-EndCommand-Shift-DownSelect to end
Ctrl-Shift-DCommand-Shift-DDuplicate selection
Ctrl-Shift-P---Select to matching bracket
Check out this site if you want to get JSON formatter tool free online.

Friday, May 26, 2017

Differences between JSON and JSONP

What are the differences between JSON and JSONP? Are they the same? Let's find out.

JSON vs JSONP

JSON is a language designed for lightweight data exchange in an format that is easy for both humans and computers to understand. See: JSON formatter for more information.
JSON language could work on a technology which is not restricted by the same origin policy with only a small amount of changes required. The combination of this tech, along with the adapted form of JSON was branded JSONP.
The new technology that is fundamental to JSONP is nothing more than the bog-standard <script> tag. 
The full power of the <script> tag is often overlooked, or at the very least, taken for granted:
  1. <script> tags are not restricted by any same origin policy, so can make requests to any domain.
  2. <script> tags can be added programatically, which allows developers to request resources via the <script> tag as and when required:
    var element = document.createElement("script"); // create the element
    element.src = 'http://somewhere.com/some/resource.js'; // set the target resource
    document.getElementsByTagName("head")[0].appendChild(element); // add the element to the DOM
  3. The src attribute of the <script> tag is not restricted to just JavaScript files. Whatever the target, it will be retrieved via the relevant transport protocol (HTTP GET/ HTTPS GET), and the content will be evaluated by the JavaScript engine. If the content is not valid JavaScript, a Parse Error will be thrown.
JSONP is JSON with padding. You put a string at the beginning and a pair of parenthesis around it. For example:



//JSON
{"name":"stackoverflow","id":5}
//JSONP
func({"name":"stackoverflow","id":5});

Thursday, May 18, 2017

JSON Arrays

Arrays as JSON Objects

Example

"Ford""BMW""Fiat" ]
As you can learn from JSON formatter, Arrays in JSON are almost the same as in JavaScript.
Array values in JSON need to be of type string, number, object, array, boolean, or null.
Array values in Javascript can be all of the above and any other valid JavaScript expression such as functions, dates, and undefined.

Arrays in JSON Objects

Arrays can be values of an object property:
{
"name":"John",
"age":30,
"cars":[ "Ford""BMW""Fiat" ]
}

Access Array Values

Access the array values by using the index number:
x = myObj.cars[0];

LoopThrough an Array

Access array values by using a for-in loop:
for (i in myObj.cars) {
    += myObj.cars[i];
}
Or use a for loop:
for (i 0; i < myObj.cars.length; i++) {
    x += myObj.cars[i];
}


Nested Arrays in JSON Objects

Values in an array can also be another array, or even another JSON object:
myObj = {
    "name":"John",
    "age":30,
    "cars": [
        { "name":"Ford""models":[ "Fiesta""Focus""Mustang" ] },
        "name":"BMW""models":[ "320""X3""X5" ] },
        "name":"Fiat""models":[ "500""Panda" ] }
    ]
 }
Use a for-in loop for each array in order to access arrays inside arrays:
for (i in myObj.cars) {
    x += "<h1>" + myObj.cars[i].name "</h1>";
    for (j in myObj.cars[i].models) {
        x += myObj.cars[i].models[j];
    }
}

Modify Array Values

Use the index number to modify an array:
 myObj.cars[1] = "Mercedes";

Delete Array Items

Use the delete keyword to delete items from an array:
delete myObj.cars[1];

Friday, May 12, 2017

JSON Parse

JSON is often used to exchange data to/from a web server. The data is always a string when you receive it from a web server. Parse the data with JSON.parse() to make it becomes a Javascript object. This site will make it easier for you if you want to get JSON formatter

PARSING JSON - EXAMPLE

Imagine we received this text from a web server:
'{ "name":"John", "age":30, "city":"New York"}'
Use the JavaScript function JSON.parse() in order to convert text into a JavaScript object:
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
Reember to make sure that the text is written in JSON format, otherwise, you will receive  a syntax error.
Use the JavaScript object in your page:

Example

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age
</script>

Friday, April 28, 2017

JSON - Comparison with XML

JSON and XML are human readable formats and are language independent. They both have support for creation, reading and decoding in real world situations. We can compare JSON with XML, based on the following factors –

Verbose

XML is more verbose than JSON, so it is faster to write JSON for programmers.

Arrays Usage

XML is used to describe the structured data, which doesn't include arrays whereas JSON include arrays.

Parsing


JavaScript's eval method parses JSON. When applied to JSON, eval returns the described object.

Example

Individual examples of XML and JSON –

JSON


{
"company":Volkswagen,
"name":"Vento",
"price":800000
}


XML

<car>
<company>Volkswagen</company>
<name>Vento</name>
<price>800000</price>
</car>

Friday, April 21, 2017

JSON – Schema:

      JSON Schema is a specification for JSON based format for defining the structure of JSON data. It was written under IETF draft which expired in 2011. JSON Schema −
  • Describes your existing data format.
  • Clear, human- and machine-readable documentation.
  • Complete structural validation, useful for automated testing.
  • Complete structural validation, validating client-submitted data.

-                    JSON Schema Validation Libraries:


There are several validators currently available for different programming languages. Currently the most complete and compliant JSON Schema validator available is JSV.
Languages
Libraries
C
WJElement (LGPLv3)
Java
json-schema-validator (LGPLv3)
.NET
Json.NET (MIT)
ActionScript 3
Frigga (MIT)
Haskell
aeson-schema (MIT)
Python
Jsonschema
Ruby
autoparse (ASL 2.0); ruby-jsonschema (MIT)
PHP
php-json-schema (MIT). json-schema (Berkeley)
JavaScript
Orderly (BSD); JSV; json-schema; Matic (MIT); Dojo; Persevere (modified BSD or AFL 2.0); schema.js.


-                   
JSON Schema Example:

Given below is a basic JSON schema, which covers a classical product catalog description –
{
"$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"
},
                 
"price":{
"type":"number",
"minimum":0,


"exclusiveMinimum":true
}
},
         
"required":["id","name","price"]
}
Let's the check various important keywords that can be used in this schema –
S. No.
Keyword & Description
1
$schema
The $schema keyword states that this schema is written according to the draft v4 specification.
2
title
You will use this to give a title to your schema.
3
description
A little description of the schema.
4
type
The type keyword defines the first constraint on our JSON data: it has to be a JSON Object.
5
properties
Defines various keys and their value types, minimum and maximum values to be used in JSON file.
6
required
This keeps a list of required properties.
7
minimum
This is the constraint to be put on the value and represents minimum acceptable value.
8
exclusiveMinimum
If "exclusiveMinimum" is present and has boolean value true, the instance is valid if it is strictly greater than the value of "minimum".
9
maximum
This is the constraint to be put on the value and represents maximum acceptable value.
10
exclusiveMaximum
If "exclusiveMaximum" is present and has boolean value true, the instance is valid if it is strictly lower than the value of "maximum".
11
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.
12
maxLength
The length of a string instance is defined as the maximum number of its characters.
13
minLength
The length of a string instance is defined as the minimum number of its characters.
14
pattern
A string instance is considered valid if the regular expression matches the instance successfully.
You can check a http://json-schema.org for the complete list of keywords that can be used in defining a JSON schema. The above schema can be used to test the validity of the following JSON code −
[
{
"id":2,
"name":"An ice sculpture",
"price":12.50,
},
         
{
"id":3,
"name":"A blue mouse",
"price":25.50,
}
]