index.js 840 B

1234567891011121314151617181920212223242526272829303132
  1. 'use strict'
  2. module.exports = parseJson
  3. function parseJson (txt, reviver, context) {
  4. context = context || 20
  5. try {
  6. return JSON.parse(txt, reviver)
  7. } catch (e) {
  8. const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i)
  9. const errIdx = syntaxErr
  10. ? +syntaxErr[1]
  11. : e.message.match(/^Unexpected end of JSON.*/i)
  12. ? txt.length - 1
  13. : null
  14. if (errIdx != null) {
  15. const start = errIdx <= context
  16. ? 0
  17. : errIdx - context
  18. const end = errIdx + context >= txt.length
  19. ? txt.length
  20. : errIdx + context
  21. e.message += ` while parsing near '${
  22. start === 0 ? '' : '...'
  23. }${txt.slice(start, end)}${
  24. end === txt.length ? '' : '...'
  25. }'`
  26. } else {
  27. e.message += ` while parsing '${txt.slice(0, context * 2)}'`
  28. }
  29. throw e
  30. }
  31. }