Results: 39
JS script below creates
<script>
element and fills with the
JSON
retrieved from a server
<script>

var obj, dbParam, xmlhttp, myObj, x, txt = "";
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.write(txt);
  }
};
xmlhttp.open("POST", "json_demo_html_table.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);

</script>
The code below calls PHP service using AJAX
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;
Nested arrays inside JSON object
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 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];
  }
}
The
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"}
When we use JSON.parse() on a JSON
derived from an array
, the method will return a JavaScript array, instead of an object
var 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();
We can request JSON (
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 object
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();
Store and retrieve data from local storage
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;
We can convert the object into JSON, and send the data to a server as a value of
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;
Most of the time,
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
.
Unsupported data types will be converted to
null
when we want to JSON.stringify the JavaScript object
document.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"]}"
Results: 39