Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

index.js 1.1KB

1234567891011121314151617181920212223242526272829303132333435363738
  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. if (typeof txt !== 'string') {
  9. const isEmptyArray = Array.isArray(txt) && txt.length === 0
  10. const errorMessage = 'Cannot parse ' +
  11. (isEmptyArray ? 'an empty array' : String(txt))
  12. throw new TypeError(errorMessage)
  13. }
  14. const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i)
  15. const errIdx = syntaxErr
  16. ? +syntaxErr[1]
  17. : e.message.match(/^Unexpected end of JSON.*/i)
  18. ? txt.length - 1
  19. : null
  20. if (errIdx != null) {
  21. const start = errIdx <= context
  22. ? 0
  23. : errIdx - context
  24. const end = errIdx + context >= txt.length
  25. ? txt.length
  26. : errIdx + context
  27. e.message += ` while parsing near '${
  28. start === 0 ? '' : '...'
  29. }${txt.slice(start, end)}${
  30. end === txt.length ? '' : '...'
  31. }'`
  32. } else {
  33. e.message += ` while parsing '${txt.slice(0, context * 2)}'`
  34. }
  35. throw e
  36. }
  37. }