str2obj.mjs

  1. import cv from './_jsonType.mjs'
  2. import isstr from './isstr.mjs'
  3. import isarr from './isarr.mjs'
  4. /**
  5. * 字串轉任意資料,可支援內含Uint8Array與Uint16Array數據
  6. *
  7. * Unit Test: {@link https://github.com/yuda-lyu/wsemi/blob/master/test/str2obj.test.mjs Github}
  8. * @memberOf wsemi
  9. * @param {*} data 輸入任意資料
  10. * @param {String|Array} [ext='Uint8Array'] 輸入擴充數據種類字串或陣列,預設'Uint8Array'
  11. * @returns {String} 回傳base64字串
  12. * @example
  13. *
  14. * console.log(str2obj('{"a":"abc","b":12.3,"u8a":"[Uint8Array]::QmFz","u16a":{"0":11,"1":79,"2":6}}'))
  15. * // => {
  16. * // => a: 'abc',
  17. * // => b: 12.3,
  18. * // => u8a: Uint8Array [ 66, 97, 115 ],
  19. * // => u16a: { '0': 11, '1': 79, '2': 6 }
  20. * // => }
  21. *
  22. * console.log(str2obj('{"a":"abc","b":12.3,"u8a":"[Uint8Array]::QmFz","u16a":"[Uint8Array]::C08G"}', ['Uint8Array', 'Uint16Array']}))
  23. * // => {
  24. * // => a: 'abc',
  25. * // => b: 12.3,
  26. * // => u8a: Uint8Array [ 66, 97, 115 ],
  27. * // => u16a: Uint8Array [ 11, 79, 6 ]
  28. * // => }
  29. *
  30. */
  31. function str2obj(data, ext = 'Uint8Array') {
  32. //ext
  33. if (isstr(ext)) {
  34. ext = [ext]
  35. }
  36. else if (isarr(ext)) {
  37. //none
  38. }
  39. else {
  40. //ext error
  41. return {}
  42. }
  43. //replacer
  44. function replacer(k, v) {
  45. if (ext.indexOf('Uint8Array') >= 0) {
  46. v = cv.b642u8arr(v)
  47. }
  48. if (ext.indexOf('Uint16Array') >= 0) {
  49. v = cv.b642u16arr(v)
  50. }
  51. return v
  52. }
  53. let s = {}
  54. try {
  55. s = JSON.parse(data, replacer)
  56. }
  57. catch (err) {
  58. s = {}
  59. }
  60. return s
  61. }
  62. export default str2obj