Skip to content

Commit

Permalink
First version of the json slicer :D
Browse files Browse the repository at this point in the history
  • Loading branch information
Amos Wenger committed Apr 13, 2011
0 parents commit a0bfdd8
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
52 changes: 52 additions & 0 deletions json-slicer.js
@@ -0,0 +1,52 @@

$(function() {
function createSelection(start, end, field) {
if (field.createTextRange) {
/* IE calculates the end of selection range based from the starting point. */
var newend = end - start;
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart("character", start);
selRange.moveEnd("character", newend);
selRange.select();
} else if (field.setSelectionRange) {
/* Other browsers calculate end of selection from the beginning of given text node. */
field.setSelectionRange(start, end);
}
field.focus();
}

function sliceAndDice(value, index) {
if(value.length == 1) {
createSelection(index - 1, index, document.getElementById('json'));
var repr = "" + value.charCodeAt(0);
while(repr.length < 4) repr = "0" + repr;
$("#result").html("Invalid character: U+" + repr);
return;
}

var half = value.length / 2;
var left = value.slice(0, half);
var right = value.slice(half);

try {
$.parseJSON("[\"" + left + "\"]");
} catch (err) {
createSelection(index - 1, index - 1 + half, document.getElementById('json'));
sliceAndDice(left, index);
}

try {
$.parseJSON("[\"" + right + "\"]");
} catch (err) {
createSelection(index - 1, index - 1 + half, document.getElementById('json'));
sliceAndDice(right, index + half);
}
}

$('#analyze').click(function() {
var value = $('#json').attr("value");

sliceAndDice(value, 0);
});
});
31 changes: 31 additions & 0 deletions slicer.html
@@ -0,0 +1,31 @@
<!DOCTYPE html>
<html>
<head>
<title>json slicer</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script src="json-slicer.js"></script>

<style>
#json {
width: 80%;
height: 200pt;
}
</style>
</head>

<p>
JSON data:
</p>

<p>
<textarea id="json" type="text"></textarea>
</p>

<p>
<input id="analyze" type="button" value="Analyze"></input>
</p>

<p id="result">
</p>

</html>

0 comments on commit a0bfdd8

Please sign in to comment.