×
Clear all filters including search bar
Valeri Tandilashvili's Personal Professional Blog
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", "demo_file.php", true);
xmlhttp.send();
PHP code that responds to the request$myArr = array("name"=>"John", "age"=>30, "city"=>"New York");
$myJSON = json_encode($myArr);
echo $myJSON;
var myObj, i, j, x = "";
myObj = {
"name":"John",
"age":30,
"cars": [
{"name":"Ford", "models":["Fiesta", "Focus", "Mustang"]},
{"name":"BMW", "models":["320", "X3", "X5"]},
{"name":"Fiat", "models":["500", "Panda"] }
]
}
To access nested JSON arraysfor (i in myObj.cars) {
x += "<h1>" + myObj.cars[i].name + "</h1>";
for (j in myObj.cars[i].models) {
x += myObj.cars[i].models[j];
}
}
JSON.stringify()
will remove functions from a JavaScript object because function
is not valid data type in JSON
var obj = { name: "John", age: function () {return 30;}, city: "New York" };
// Functions and any other unsupported data types will be ignored
var myJSON = JSON.stringify(obj);
document.write(myJSON);
The result will be:{"name":"John","city":"New York"}
As we can see, the function
is removed. To solve this issue we can convert the function into string
before running stringify
var obj = { name: "John", age: function () {return 30;}, city: "New York" };
obj.age = obj.age.toString();
var myJSON = JSON.stringify(obj);
document.write(myJSON);
The result will be:{"name":"John","age":"function () {return 30;}","city":"New York"}
derived from an array
, the method will return a JavaScript array, instead of an objectvar xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myArr[0];
}
};
xmlhttp.open("GET", "json_demo_array.txt", true);
xmlhttp.send();
derived from an object
) from the server by using an XMLHttpRequest request
As long as the response from the server is written in JSON format, we can parse the JSON data into a JavaScript objectvar 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();
let myObj, myJSON, text, obj;
// Storing data:
myObj = { name: "John", age: 31, city: "New York" };
myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
// Retrieving data:
text = localStorage.getItem("testJSON");
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name + ' is ' + obj.age;
x
variable (but it's not ideal way of sending JSON to a server)var myObj = {name: "John", age: 31, city: "New York"};
var myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;
JSON.stringify
is used with the first argument only.
But if we need to fine-tune the replacement process, like to filter out circular references
, we can use the second argument of JSON.stringify
let room = {
number: 23
};
let meetup = {
title: "Conference",
participants: [{name: "John"}, {name: "Alice"}],
place: room // meetup references room
};
room.occupiedBy = meetup; // room references meetup
document.write( JSON.stringify(meetup, ['title', 'participants']) );
If we pass an array of properties to it, only these properties will be encoded, so the result will be:{"title":"Conference","participants":[{},{}]}
As the result shows, the property list is applied to the whole object structure. So the objects in participants
are empty, because name
is not in the list.
Let’s include in the list every property except room.occupiedBy
that would cause the circular reference:let room = {
number: 23
};
let meetup = {
title: "Conference",
participants: [{name: "John"}, {name: "Alice"}],
place: room // meetup references room
};
room.occupiedBy = meetup; // room references meetup
document.write( JSON.stringify(meetup, ['title', 'participants', 'place', 'name', 'number']) );
The result will be:{"title":"Conference","participants":[{"name":"John"},{"name":"Alice"}],"place":{"number":23}}
Now everything except occupiedBy
is serialized. But the list of properties is quite long.
Fortunately, we can use a function instead of an array as the replacer
.null
when we want to JSON.stringify the JavaScript objectdocument.write(JSON.stringify({ x: 5, y: 6 }) + "<br />");
// expected output: "{"x":5,"y":6}"
document.write(JSON.stringify([new Number(3), new String('false'), new Boolean(false)]) + "<br />");
// expected output: "[3,"false",false]"
document.write(JSON.stringify({ x: [10, undefined, function(){}, Symbol('d'), new Date(2006, 0, 2, 15, 4, 5)] }) + "<br />");
// expected output: "{"x":[10,null,null,null,"2006-01-02T11:04:05.000Z"]}"