Friday, January 5, 2018

JSON.stringify()

Convert a JavaScript object into a string with JSON.stringify().

JSON.stringify()

Stringify a JavaScript Object

Imagine we have this object in JavaScript:
var obj = { "name":"John""age":30"city":"New York"};
Use the JavaScript function JSON.stringify() to convert it into a string.
var myJSON = JSON.stringify(obj);
The result will be a string following the JSON notation.
myJSON is now a string, and ready to be sent to a server:

Example

var obj = { "name":"John""age":30"city":"New York"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
You will learn how to send JSON to the server in the next chapter.

Stringify a JavaScript Array

It is also possible to stringify JavaScript arrays:
Imagine we have this array in JavaScript:
var arr = [ "John""Peter""Sally""Jane" ];
Use the JavaScript function JSON.stringify() to convert it into a string.
var myJSON = JSON.stringify(arr);
The result will be a string following the JSON notation.
myJSON is now a string, and ready to be sent to a server:

Example

var arr = [ "John""Peter""Sally""Jane" ];
var myJSON = JSON.stringify(arr);
document.getElementById("demo").innerHTML = myJSON;

Exceptions

Stringify Dates

In JSON, date objects are not allowed. The JSON.stringify() function will convert any dates into strings.

Example

var obj = "name":"John""today":new Date(), "city":"New York"};
var myJSON = JSON.stringify(obj);

document.getElementById("demo").innerHTML = myJSON;
You can convert the string back into a date object at the receiver.

Stringify Functions

In JSON, functions are not allowed as object values.
The JSON.stringify() function will remove any functions from a JavaScript object, both the key and the value:

Example

var obj = "name":"John""age":function () {return 30;}, "city":"New York"};
var myJSON = JSON.stringify(obj);

document.getElementById("demo").innerHTML = myJSON;
This can be omitted if you convert your functions into strings before running the JSON.stringify() function.

Example

var obj = "name":"John""age":function () {return 30;}, "city":"New York"};
obj.age = obj.age.toString();
var myJSON = JSON.stringify(obj);

document.getElementById("demo").innerHTML = myJSON;
Use this tool to edit, convert, format, and validate JSON: JSON formatter online tool

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>