JSON.stringify Examples

by Stefan Wetter

HTML

<input type="button" id="clickme" value="Show Results">
<div id="results"></div>

CSS

.header {
    font-family: Arial;
    background-color: MidnightBlue;
    color: white;
 	margin-top: 2em;   
    padding: .25em;
    border-top: 1pt solid SteelBlue;
    border-bottom: 1pt solid SteelBlue;
}

JavaScript

var dummy = {
    url: "http://lala.com?la=vy"
};

// the values aren't used, just the keys
var doNotStringify = {
    currentTarget: true,
    delegateTarget: true,
    originalEvent: true,
    target: true,
    toElement: true,
    view : true
}

function writeToDom(title, content) {
    $("#results").append("<div class='header'>" + title + ":</div><div><pre>" + content + "</pre></div>");
}

function showResults(evnt) {
    writeToDom('Plain', JSON.stringify(dummy));
    writeToDom('Formatted', JSON.stringify(dummy, null, 4));
    writeToDom('Plucked From Event via Replacer Array', JSON.stringify(evnt, [ "clientX", "clientY", "offsetX", "offsetY" ], 4));
    writeToDom('Plucked From Event via Replacer Fn', JSON.stringify(evnt, function(key, value) {
        var result = value;
        if(doNotStringify.hasOwnProperty(key)) {
            result = undefined;
        }
        return result;
    }, 4));
}

$(function() {
   $(document).on("click", "#clickme", showResults); 
});