JSON.stringify
JSON.stringify
HTML
<input type="button" id="clickme" value="Show Results">
<div id="results"></div>
CSS
.header {
font-family: Arial;
background-color: OrangeRed;
color: white;
margin-top: 2em;
padding: .25em;
border-top: 1pt solid DarkViolet;
border-bottom: 1pt solid DarkViolet;
}
JavaScript
var person = {
name: "Casiano Rodriguez",location: {city: {name: "La Laguna",population: 3000
},
state: {
name: "Tenerife",
abbreviation: "TF",
population: 700000
}
},
company: "Universidad de La Laguna",
};
// the values aren't used, just the keys
var doNotStringify = {
abbreviation: true,
population: true
};
function writeToDom(title, content) {
$("#results").append("<div class='header'>" + title + ":</div><div><pre>" + content + "</pre></div>");
}
function showResults(evnt) {
writeToDom('Plain', JSON.stringify(person));
writeToDom('Formatted', JSON.stringify(person, null, 4));
writeToDom('Plucked From Event via Replacer Array',
JSON.stringify(person, ["name", "location", "city", "state"], 4));
writeToDom('Plucked From Event via Replacer Fn',
JSON.stringify(person, function (key, value) {
var result = value;
if (doNotStringify.hasOwnProperty(key)) {
result = undefined;
}
return result;
}, 4));
}
$(function () {
$(document).on("click", "#clickme", showResults);
});