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.

83 lines
1.2 KiB

4 years ago
  1. # parse-json [![Build Status](https://travis-ci.org/sindresorhus/parse-json.svg?branch=master)](https://travis-ci.org/sindresorhus/parse-json)
  2. > Parse JSON with more helpful errors
  3. ## Install
  4. ```
  5. $ npm install parse-json
  6. ```
  7. ## Usage
  8. ```js
  9. const parseJson = require('parse-json');
  10. const json = '{\n\t"foo": true,\n}';
  11. JSON.parse(json);
  12. /*
  13. undefined:3
  14. }
  15. ^
  16. SyntaxError: Unexpected token }
  17. */
  18. parseJson(json);
  19. /*
  20. JSONError: Trailing comma in object at 3:1
  21. }
  22. ^
  23. */
  24. parseJson(json, 'foo.json');
  25. /*
  26. JSONError: Trailing comma in object in foo.json:3:1
  27. }
  28. ^
  29. */
  30. // You can also add the filename at a later point
  31. try {
  32. parseJson(json);
  33. } catch (err) {
  34. err.fileName = 'foo.json';
  35. throw err;
  36. }
  37. /*
  38. JSONError: Trailing comma in object in foo.json:3:1
  39. }
  40. ^
  41. */
  42. ```
  43. ## API
  44. ### parseJson(input, [reviver], [filename])
  45. #### input
  46. Type: `string`
  47. #### reviver
  48. Type: `Function`
  49. Prescribes how the value originally produced by parsing is transformed, before being returned. See [`JSON.parse` docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter
  50. ) for more.
  51. #### filename
  52. Type: `string`
  53. Filename displayed in the error message.
  54. ## License
  55. MIT © [Sindre Sorhus](https://sindresorhus.com)