You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

31 lines
873 B

7 years ago
  1. /**
  2. * JSON parse.
  3. *
  4. * @see Based on jQuery#parseJSON (MIT) and JSON2
  5. * @api private
  6. */
  7. var rvalidchars = /^[\],:{}\s]*$/;
  8. var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
  9. var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  10. var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
  11. var rtrimLeft = /^\s+/;
  12. var rtrimRight = /\s+$/;
  13. module.exports = function parsejson(data) {
  14. if ('string' != typeof data || !data) {
  15. return null;
  16. }
  17. data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
  18. // Attempt to parse using the native JSON parser first
  19. if (global.JSON && JSON.parse) {
  20. return JSON.parse(data);
  21. }
  22. if (rvalidchars.test(data.replace(rvalidescape, '@')
  23. .replace(rvalidtokens, ']')
  24. .replace(rvalidbraces, ''))) {
  25. return (new Function('return ' + data))();
  26. }
  27. };