jsonator

Do stuff with JSON data.

by ryanttb

HTML

<label for="source" class="json">Source data</label>
<textarea id="source" name="source"></textarea>

<label><span>argument</span> <input type="text" id="a1" value="" /></label>

<button type="button">GO!</button>

<label for="dest" class="json">Output</label>
<textarea id="dest" name="dest"></textarea>

CSS

button, label {
    display: block;
}
label span {
    display: inline-block;
    width: 12em;
}

textarea {
    width: 80%;
    height: 10em;
}

JavaScript

$("button").click(function() {
    $("#dest").val("");

    var source;
    var item;
    var args = {};
    var allArgsValid = true;
    
    $("input").each(function() {
        if (!this.value) {
            allArgsValid = false;
            return false;
        } else {
            args[this.id] = this.value;
        }
    });
    
    try {
        source = JSON.parse($("#source").val());
    } catch (e) { }

    if (!source || !$.isArray(source)) {
        $("#dest").val("source is not a JSON array");
    } else if (!allArgsValid) {
        $("#dest").val("all input and output fields are required");
    } else {
        for (var i = 0; i < source.length; i++) {
            item = source[i];
            // do stuff with item
        }
        
        $("#dest").val(JSON.stringify(source));
    }
});