JsonParser.JsonParser.patch Maven / Gradle / Ivy
--- C:/Work/JOYn/workspace/dev/javascript/atmosphere-messaging/src/main/js/lib/json/json_parse_state.js Mon Mar 11 15:45:36 2013
+++ C:/Work/JOYn/workspace/dev/javascript/atmosphere-messaging/src/main/js/lib/json/JsonParser.js Mon Mar 11 15:52:53 2013
@@ -1,4 +1,13 @@
-/*
+/* Modified from Douglas Crockford's json_parse_state.js (2012-06-01)
+ ... in order to support concatenated JSON strings sent via Atmospehere:
+
+ JSON of the form: {object1}{object2} is parsed using an iterator paradigm:
+
+ var parser = new JsonParser(concatenatedJsonString)
+ while (parser.hasNext) {
+ var obj = parser.next;
+ }
+
json_parse_state.js
2012-06-01
@@ -55,9 +64,14 @@
value, "{", "}"
*/
-var json_parse = (function() {
+function JsonParser(source, reviver) {
"use strict";
+ /**
+ * whether a further json object has been detected in the string being parsed.
+ */
+ this.hasNext = source.length > 0;
+
// This function creates a JSON parse function that uses a state machine
// rather
// than the dangerous eval function to parse a JSON text.
@@ -164,6 +178,12 @@
});
container = {};
state = 'firstokey';
+ },
+ //we reach here when the first object in a string concatenation has been found
+ // exist parse and allow next object to be found on next call to next()
+ ok: function() {
+ state = "hasNext";
+ throw "hasNext";
}
},
'}' : {
@@ -317,7 +337,16 @@
});
}
- return function(source, reviver) {
+ /**
+ * @returns the next object found in the string being parsed. Call in while loop while
+ *
+ * while (parser.hasNext) {
+ * var next = parser.next;
+ */
+ this.next = {};
+ Object.defineProperty(this, 'next', {
+ configurable: false,
+ get: function() {
// A regular expression is used to extract tokens from the JSON text.
// The extraction process is cautious.
@@ -404,10 +433,17 @@
// the
// remaining source contains anything except whitespace, then we did not
// have
- // a well-formed JSON text.
+ // a well-formed JSON text (unless another object begins here)
+
+ if (state !== 'ok' && state !== 'hasNext' ) {
+ throw state instanceof SyntaxError ? state
+ : new SyntaxError('JSON');
+ }
- if (state !== 'ok' || /[^\x20\t\n\r]/.test(source)) {
- throw state instanceof SyntaxError ? state : new SyntaxError('JSON');
+ if (state === "hasNext") {
+ this.hasNext = true;
+ } else {
+ this.hasNext = false;
}
// If there is a reviver function, we recursively walk the new
@@ -437,5 +473,6 @@
}({
'' : value
}, '')) : value;
- };
-}());
+ }
+ });
+}