stringify.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import BigNumber from "bignumber.js-master"
  2. // var BigNumber = require('bignumber.js');
  3. /*
  4. json2.js
  5. 2013-05-26
  6. Public Domain.
  7. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
  8. See http://www.JSON.org/js.html
  9. This code should be minified before deployment.
  10. See http://javascript.crockford.com/jsmin.html
  11. USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
  12. NOT CONTROL.
  13. This file creates a global JSON object containing two methods: stringify
  14. and parse.
  15. JSON.stringify(value, replacer, space)
  16. value any JavaScript value, usually an object or array.
  17. replacer an optional parameter that determines how object
  18. values are stringified for objects. It can be a
  19. function or an array of strings.
  20. space an optional parameter that specifies the indentation
  21. of nested structures. If it is omitted, the text will
  22. be packed without extra whitespace. If it is a number,
  23. it will specify the number of spaces to indent at each
  24. level. If it is a string (such as '\t' or ' '),
  25. it contains the characters used to indent at each level.
  26. This method produces a JSON text from a JavaScript value.
  27. When an object value is found, if the object contains a toJSON
  28. method, its toJSON method will be called and the result will be
  29. stringified. A toJSON method does not serialize: it returns the
  30. value represented by the name/value pair that should be serialized,
  31. or undefined if nothing should be serialized. The toJSON method
  32. will be passed the key associated with the value, and this will be
  33. bound to the value
  34. For example, this would serialize Dates as ISO strings.
  35. Date.prototype.toJSON = function (key) {
  36. function f(n) {
  37. // Format integers to have at least two digits.
  38. return n < 10 ? '0' + n : n;
  39. }
  40. return this.getUTCFullYear() + '-' +
  41. f(this.getUTCMonth() + 1) + '-' +
  42. f(this.getUTCDate()) + 'T' +
  43. f(this.getUTCHours()) + ':' +
  44. f(this.getUTCMinutes()) + ':' +
  45. f(this.getUTCSeconds()) + 'Z';
  46. };
  47. You can provide an optional replacer method. It will be passed the
  48. key and value of each member, with this bound to the containing
  49. object. The value that is returned from your method will be
  50. serialized. If your method returns undefined, then the member will
  51. be excluded from the serialization.
  52. If the replacer parameter is an array of strings, then it will be
  53. used to select the members to be serialized. It filters the results
  54. such that only members with keys listed in the replacer array are
  55. stringified.
  56. Values that do not have JSON representations, such as undefined or
  57. functions, will not be serialized. Such values in objects will be
  58. dropped; in arrays they will be replaced with null. You can use
  59. a replacer function to replace those with JSON values.
  60. JSON.stringify(undefined) returns undefined.
  61. The optional space parameter produces a stringification of the
  62. value that is filled with line breaks and indentation to make it
  63. easier to read.
  64. If the space parameter is a non-empty string, then that string will
  65. be used for indentation. If the space parameter is a number, then
  66. the indentation will be that many spaces.
  67. Example:
  68. text = JSON.stringify(['e', {pluribus: 'unum'}]);
  69. // text is '["e",{"pluribus":"unum"}]'
  70. text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
  71. // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
  72. text = JSON.stringify([new Date()], function (key, value) {
  73. return this[key] instanceof Date ?
  74. 'Date(' + this[key] + ')' : value;
  75. });
  76. // text is '["Date(---current time---)"]'
  77. JSON.parse(text, reviver)
  78. This method parses a JSON text to produce an object or array.
  79. It can throw a SyntaxError exception.
  80. The optional reviver parameter is a function that can filter and
  81. transform the results. It receives each of the keys and values,
  82. and its return value is used instead of the original value.
  83. If it returns what it received, then the structure is not modified.
  84. If it returns undefined then the member is deleted.
  85. Example:
  86. // Parse the text. Values that look like ISO date strings will
  87. // be converted to Date objects.
  88. myData = JSON.parse(text, function (key, value) {
  89. var a;
  90. if (typeof value === 'string') {
  91. a =
  92. /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
  93. if (a) {
  94. return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
  95. +a[5], +a[6]));
  96. }
  97. }
  98. return value;
  99. });
  100. myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
  101. var d;
  102. if (typeof value === 'string' &&
  103. value.slice(0, 5) === 'Date(' &&
  104. value.slice(-1) === ')') {
  105. d = new Date(value.slice(5, -1));
  106. if (d) {
  107. return d;
  108. }
  109. }
  110. return value;
  111. });
  112. This is a reference implementation. You are free to copy, modify, or
  113. redistribute.
  114. */
  115. /*jslint evil: true, regexp: true */
  116. /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
  117. call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
  118. getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
  119. lastIndex, length, parse, prototype, push, replace, slice, stringify,
  120. test, toJSON, toString, valueOf
  121. */
  122. // Create a JSON object only if one does not already exist. We create the
  123. // methods in a closure to avoid creating global variables.
  124. var JSON = module.exports;
  125. (function () {
  126. 'use strict';
  127. function f(n) {
  128. // Format integers to have at least two digits.
  129. return n < 10 ? '0' + n : n;
  130. }
  131. var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  132. escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  133. gap,
  134. indent,
  135. meta = { // table of character substitutions
  136. '\b': '\\b',
  137. '\t': '\\t',
  138. '\n': '\\n',
  139. '\f': '\\f',
  140. '\r': '\\r',
  141. '"' : '\\"',
  142. '\\': '\\\\'
  143. },
  144. rep;
  145. function quote(string) {
  146. // If the string contains no control characters, no quote characters, and no
  147. // backslash characters, then we can safely slap some quotes around it.
  148. // Otherwise we must also replace the offending characters with safe escape
  149. // sequences.
  150. escapable.lastIndex = 0;
  151. return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
  152. var c = meta[a];
  153. return typeof c === 'string'
  154. ? c
  155. : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  156. }) + '"' : '"' + string + '"';
  157. }
  158. function str(key, holder) {
  159. // Produce a string from holder[key].
  160. var i, // The loop counter.
  161. k, // The member key.
  162. v, // The member value.
  163. length,
  164. mind = gap,
  165. partial,
  166. value = holder[key],
  167. isBigNumber = value != null && (value instanceof BigNumber || BigNumber.isBigNumber(value));
  168. // If the value has a toJSON method, call it to obtain a replacement value.
  169. if (value && typeof value === 'object' &&
  170. typeof value.toJSON === 'function') {
  171. value = value.toJSON(key);
  172. }
  173. // If we were called with a replacer function, then call the replacer to
  174. // obtain a replacement value.
  175. if (typeof rep === 'function') {
  176. value = rep.call(holder, key, value);
  177. }
  178. // What happens next depends on the value's type.
  179. switch (typeof value) {
  180. case 'string':
  181. if (isBigNumber) {
  182. return value;
  183. } else {
  184. return quote(value);
  185. }
  186. case 'number':
  187. // JSON numbers must be finite. Encode non-finite numbers as null.
  188. return isFinite(value) ? String(value) : 'null';
  189. case 'boolean':
  190. case 'null':
  191. case 'bigint':
  192. // If the value is a boolean or null, convert it to a string. Note:
  193. // typeof null does not produce 'null'. The case is included here in
  194. // the remote chance that this gets fixed someday.
  195. return String(value);
  196. // If the type is 'object', we might be dealing with an object or an array or
  197. // null.
  198. case 'object':
  199. // Due to a specification blunder in ECMAScript, typeof null is 'object',
  200. // so watch out for that case.
  201. if (!value) {
  202. return 'null';
  203. }
  204. // Make an array to hold the partial results of stringifying this object value.
  205. gap += indent;
  206. partial = [];
  207. // Is the value an array?
  208. if (Object.prototype.toString.apply(value) === '[object Array]') {
  209. // The value is an array. Stringify every element. Use null as a placeholder
  210. // for non-JSON values.
  211. length = value.length;
  212. for (i = 0; i < length; i += 1) {
  213. partial[i] = str(i, value) || 'null';
  214. }
  215. // Join all of the elements together, separated with commas, and wrap them in
  216. // brackets.
  217. v = partial.length === 0
  218. ? '[]'
  219. : gap
  220. ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
  221. : '[' + partial.join(',') + ']';
  222. gap = mind;
  223. return v;
  224. }
  225. // If the replacer is an array, use it to select the members to be stringified.
  226. if (rep && typeof rep === 'object') {
  227. length = rep.length;
  228. for (i = 0; i < length; i += 1) {
  229. if (typeof rep[i] === 'string') {
  230. k = rep[i];
  231. v = str(k, value);
  232. if (v) {
  233. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  234. }
  235. }
  236. }
  237. } else {
  238. // Otherwise, iterate through all of the keys in the object.
  239. Object.keys(value).forEach(function(k) {
  240. var v = str(k, value);
  241. if (v) {
  242. partial.push(quote(k) + (gap ? ': ' : ':') + v);
  243. }
  244. });
  245. }
  246. // Join all of the member texts together, separated with commas,
  247. // and wrap them in braces.
  248. v = partial.length === 0
  249. ? '{}'
  250. : gap
  251. ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
  252. : '{' + partial.join(',') + '}';
  253. gap = mind;
  254. return v;
  255. }
  256. }
  257. // If the JSON object does not yet have a stringify method, give it one.
  258. if (typeof JSON.stringify !== 'function') {
  259. JSON.stringify = function (value, replacer, space) {
  260. // The stringify method takes a value and an optional replacer, and an optional
  261. // space parameter, and returns a JSON text. The replacer can be a function
  262. // that can replace values, or an array of strings that will select the keys.
  263. // A default replacer method can be provided. Use of the space parameter can
  264. // produce text that is more easily readable.
  265. var i;
  266. gap = '';
  267. indent = '';
  268. // If the space parameter is a number, make an indent string containing that
  269. // many spaces.
  270. if (typeof space === 'number') {
  271. for (i = 0; i < space; i += 1) {
  272. indent += ' ';
  273. }
  274. // If the space parameter is a string, it will be used as the indent string.
  275. } else if (typeof space === 'string') {
  276. indent = space;
  277. }
  278. // If there is a replacer, it must be a function or an array.
  279. // Otherwise, throw an error.
  280. rep = replacer;
  281. if (replacer && typeof replacer !== 'function' &&
  282. (typeof replacer !== 'object' ||
  283. typeof replacer.length !== 'number')) {
  284. throw new Error('JSON.stringify');
  285. }
  286. // Make a fake root object containing our value under the key of ''.
  287. // Return the result of stringifying the value.
  288. return str('', {'': value});
  289. };
  290. }
  291. }());