JSON : JavaScript Object Notation.
JSON is a syntax for storing and exchanging data.
JSON is text, written with JavaScript object notation.
JSON syntax is derived from JavaScript object notation syntax
In JSON, values must be one of the following data types:
- a string
- a number
- an object
- an array
- a boolean
- null
In JavaScript values can be all of the above, plus any other valid JavaScript expression, including
- a function
- a date
- undeifined
JSON.parse()
- A common use of JSON is to exchange data to/from a web server.
- When receiving data from a web server, the data is always a string.
- Parse the data with JSON.parse(), and the data becomes a JavaScript object.
Example :
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
</script>
JSON.stringify()
- A common use of JSON is to exchange data to/from a web server.
- When sending data to a web server, the data has to be a string.
- Convert a JavaScript object into a string with JSON.stringify().
Example :
var obj = { name: "John", age: 30, city: "New York" };
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
No comments:
Post a Comment