版博士V2.0程序
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

50 řádky
1.4 KiB

  1. /**
  2. * @since 2.10.0
  3. */
  4. import { tryCatch } from './Either';
  5. import { identity } from './function';
  6. /**
  7. * Converts a JavaScript Object Notation (JSON) string into a `Json` type.
  8. *
  9. * @example
  10. * import * as J from 'fp-ts/Json'
  11. * import * as E from 'fp-ts/Either'
  12. * import { pipe } from 'fp-ts/function'
  13. *
  14. * assert.deepStrictEqual(pipe('{"a":1}', J.parse), E.right({ a: 1 }))
  15. * assert.deepStrictEqual(pipe('{"a":}', J.parse), E.left(new SyntaxError('Unexpected token } in JSON at position 5')))
  16. *
  17. * @since 2.10.0
  18. */
  19. export var parse = function (s) { return tryCatch(function () { return JSON.parse(s); }, identity); };
  20. /**
  21. * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
  22. *
  23. * @example
  24. * import * as E from 'fp-ts/Either'
  25. * import * as J from 'fp-ts/Json'
  26. * import { pipe } from 'fp-ts/function'
  27. *
  28. * assert.deepStrictEqual(J.stringify({ a: 1 }), E.right('{"a":1}'))
  29. * const circular: any = { ref: null }
  30. * circular.ref = circular
  31. * assert.deepStrictEqual(
  32. * pipe(
  33. * J.stringify(circular),
  34. * E.mapLeft(e => e instanceof Error && e.message.includes('Converting circular structure to JSON'))
  35. * ),
  36. * E.left(true)
  37. * )
  38. *
  39. * @since 2.10.0
  40. */
  41. export var stringify = function (a) {
  42. return tryCatch(function () {
  43. var s = JSON.stringify(a);
  44. if (typeof s !== 'string') {
  45. throw new Error('Converting unsupported structure to JSON');
  46. }
  47. return s;
  48. }, identity);
  49. };