-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjp.js
76 lines (62 loc) · 1.95 KB
/
jp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*jslint indent: 2, maxlen: 80, continue: false, unparam: false */
/* -*- tab-width: 2 -*- */
/*global define: true, module: true, require: true */
((typeof define === 'function') && define.amd ? define : function (factory) {
'use strict';
var m = ((typeof module === 'object') && module), e = (m && m.exports);
if (e) { m.exports = (factory(require, e, m) || m.exports); }
})(function () {
'use strict';
var EX = function parseJson(json, opts) {
opts = (opts || false);
var d = EX.dareParse(json);
return (d.caught ? EX.hadErr(d.err, json, opts) : d.data);
};
EX.dareParse = function dareParse(json) {
try {
return { data: JSON.parse(json) };
} catch (jsonParseErr) {
return { caught: true, err: jsonParseErr };
}
};
EX.hadErr = function hadErr(err, origJson, opts) {
err = EX.chkErr(err, origJson);
err.input = origJson;
var hnd = (err.isSyntaxError ? opts.synErr : (opts.othErr || true));
if (!hnd) { return hnd; }
if (hnd === true) { throw err; }
if (typeof hnd === 'function') { return hnd(err); }
return hnd;
};
EX.chkErr = function chkErr(err, origJson) {
var et = (err === null ? 'null' : typeof err), s, m, p;
if (et !== 'object') {
et = new Error('Caught a non-object (' + et + ') error: ' + String(err));
et.origValue = err;
et.isSyntaxError = false;
return et;
}
s = String(err);
err.isSyntaxError = ((err instanceof SyntaxError)
|| /^SyntaxError: /i.test(s));
m = / in JSON at position (\d+)$/.exec(s);
if (m) {
if (!origJson) {
if (origJson === '') { err.message += ' (input was empty)'; }
return err;
}
origJson = String(origJson);
p = origJson.slice(m[1] - 1);
m = 128;
if (p.length > m) {
p = p.slice(0, m);
m = '…';
} else {
m = '';
}
err.message += ': ' + JSON.stringify(p) + m;
}
return err;
};
return EX;
});