Created
April 5, 2013 20:12
-
-
Save JoeRobich/5322257 to your computer and use it in GitHub Desktop.
Simple incomplete JSON parser written in pegjs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
function createObject(kvps) { | |
var object = {}; | |
for (var index = 0; index < kvps.length; index++) { | |
var value = kvps[index].value; | |
value = value == undefined ? null : value; | |
object[kvps[index].key] = value; | |
} | |
return object; | |
} | |
function createNumber(sign, integer, decimal) { | |
var number = sign + integer.join('') + '.' + decimal.join(''); | |
return parseFloat(number); | |
} | |
function createArray(items) { | |
var array = []; | |
for (var index = 0; index < items.length; index++) { | |
var value = items[index] == undefined ? null : items[index]; | |
array.push(value); | |
} | |
return array; | |
} | |
} | |
start = json | |
json = null / boolean / object / array / string / number | |
array = '[' _ items:itemlist? _ ']' _ | |
{ return createArray(items); } | |
itemlist = first:json rest:(',' _ item:json { return item; })* | |
{ return [first].concat(rest ? rest : [] ); } | |
object = '{' _ kvps:kvplist? _ '}' _ | |
{ return createObject(kvps); } | |
kvplist = first:kvp rest:(',' _ kvp:kvp { return kvp; })* | |
{ return [first].concat(rest ? rest : []); } | |
kvp = key:string _ ':' _ value:json _ | |
{ return { key:key, value:value }; } | |
string = '"' letters:letters '"' _ | |
{ return letters; } | |
letters = letters:letter* | |
{ return letters ? letters.join('') : ""; } | |
letter = (!'"' letter:. { return letter;}) | |
number = sign:'-'? i:digits d:('.' d:digits { return d; })? _ | |
{ return createNumber(sign, i, d ? d : []); } | |
digits = digits:digit+ | |
{ return digits ? digits : []; } | |
digit = [0-9] | |
boolean = true / false _ | |
true = 'true' | |
{ return true; } | |
false = 'false' | |
{ return false; } | |
null = 'null' _ | |
{ return undefined; } | |
_ = [ \t\n\r]* |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment