@@ -23,6 +23,11 @@ function TopDiff(type, diff) {
2323 this . diff = diff ;
2424}
2525
26+ function ValidationException ( leftError , rightError ) {
27+ this . leftError = leftError ;
28+ this . rightError = rightError ;
29+ }
30+
2631//// MAIN FUNCTION
2732function getDiffRepresentation ( left , right ) {
2833
@@ -154,14 +159,32 @@ function getDiffRepresentation(left, right) {
154159 return a . key > b . key ? 1 : ( b . key > a . key ) ? - 1 : 0 ;
155160 }
156161
157- var leftJson = JSON . parse ( left ) ;
158- var rightJson = JSON . parse ( right ) ;
162+ function _parseJson ( input ) {
163+ var parsedJson = null ;
164+ try {
165+ parsedJson = JSON . parse ( input ) ;
166+ } catch ( err ) {
167+ return { "json" : null , "exception" : "Input is not a valid JSON" } ;
168+ }
169+
170+ var jsonType = _getType ( parsedJson ) ;
171+ return jsonType === ARRAY || jsonType === OBJECT ?
172+ { "json" : parsedJson , "exception" : null } : { "json" : parsedJson , "exception" : "Input is not a valid JSON" } ;
173+ }
174+
175+ var leftParseResult = _parseJson ( left ) ;
176+ var rightParseResult = _parseJson ( right ) ;
177+
178+ if ( leftParseResult [ "exception" ] !== null || rightParseResult [ "exception" ] !== null ) throw new ValidationException ( leftErrors , rightErrors ) ;
179+
180+ var leftJson = leftParseResult [ "json" ] ; var rightJson = rightParseResult [ "json" ] ;
181+ var leftJsonType = _getType ( leftParseResult [ "json" ] ) ; var rightJsonType = _getType ( rightParseResult [ "json" ] ) ;
159182
160- if ( leftJson instanceof Array && rightJson instanceof Array ) return new TopDiff ( ARRAY , _getArraysDiff ( leftJson , rightJson ) ) ;
161- else if ( ! ( leftJson instanceof Array ) && ! ( rightJson instanceof Array ) ) return new TopDiff ( OBJECT , _getJsonsDiff ( leftJson , rightJson ) ) ;
183+ if ( leftJsonType === ARRAY && rightJsonType === ARRAY ) return new TopDiff ( ARRAY , _getArraysDiff ( leftJson , rightJson ) ) ;
184+ else if ( leftJsonType === OBJECT && rightJsonType === OBJECT ) return new TopDiff ( OBJECT , _getJsonsDiff ( leftJson , rightJson ) ) ;
162185 else {
163- var leftOutput = new Diff ( null , _getInDepthDiff ( leftJson , ADD ) , ADD , _getType ( leftJson ) ) ;
164- var rightOutput = new Diff ( null , _getInDepthDiff ( rightJson , REMOVE ) , REMOVE , _getType ( rightJson ) ) ;
186+ var leftOutput = new Diff ( null , _getInDepthDiff ( leftJson , ADD ) , ADD , leftJsonType ) ;
187+ var rightOutput = new Diff ( null , _getInDepthDiff ( rightJson , REMOVE ) , REMOVE , rightJsonType ) ;
165188 return new TopDiff ( NONE , [ leftOutput , rightOutput ] ) ;
166189 }
167190}
0 commit comments