@qubit-ltd/json 1.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +219 -0
  3. package/README.zh_CN.md +194 -0
  4. package/dist/json.cjs +623 -0
  5. package/dist/json.cjs.map +1 -0
  6. package/dist/json.min.cjs +1 -0
  7. package/dist/json.min.cjs.map +1 -0
  8. package/dist/json.min.mjs +1 -0
  9. package/dist/json.min.mjs.map +1 -0
  10. package/dist/json.mjs +610 -0
  11. package/dist/json.mjs.map +1 -0
  12. package/doc/api/LosslessNumber.html +610 -0
  13. package/doc/api/fonts/OpenSans-Bold-webfont.eot +0 -0
  14. package/doc/api/fonts/OpenSans-Bold-webfont.svg +1838 -0
  15. package/doc/api/fonts/OpenSans-Bold-webfont.woff +0 -0
  16. package/doc/api/fonts/OpenSans-BoldItalic-webfont.eot +0 -0
  17. package/doc/api/fonts/OpenSans-BoldItalic-webfont.svg +1838 -0
  18. package/doc/api/fonts/OpenSans-BoldItalic-webfont.woff +0 -0
  19. package/doc/api/fonts/OpenSans-Italic-webfont.eot +0 -0
  20. package/doc/api/fonts/OpenSans-Italic-webfont.svg +1838 -0
  21. package/doc/api/fonts/OpenSans-Italic-webfont.woff +0 -0
  22. package/doc/api/fonts/OpenSans-Light-webfont.eot +0 -0
  23. package/doc/api/fonts/OpenSans-Light-webfont.svg +1839 -0
  24. package/doc/api/fonts/OpenSans-Light-webfont.woff +0 -0
  25. package/doc/api/fonts/OpenSans-LightItalic-webfont.eot +0 -0
  26. package/doc/api/fonts/OpenSans-LightItalic-webfont.svg +1843 -0
  27. package/doc/api/fonts/OpenSans-LightItalic-webfont.woff +0 -0
  28. package/doc/api/fonts/OpenSans-Regular-webfont.eot +0 -0
  29. package/doc/api/fonts/OpenSans-Regular-webfont.svg +1839 -0
  30. package/doc/api/fonts/OpenSans-Regular-webfont.woff +0 -0
  31. package/doc/api/fonts/OpenSans-Semibold-webfont.eot +0 -0
  32. package/doc/api/fonts/OpenSans-Semibold-webfont.svg +1838 -0
  33. package/doc/api/fonts/OpenSans-Semibold-webfont.ttf +0 -0
  34. package/doc/api/fonts/OpenSans-Semibold-webfont.woff +0 -0
  35. package/doc/api/fonts/OpenSans-SemiboldItalic-webfont.eot +0 -0
  36. package/doc/api/fonts/OpenSans-SemiboldItalic-webfont.svg +1838 -0
  37. package/doc/api/fonts/OpenSans-SemiboldItalic-webfont.ttf +0 -0
  38. package/doc/api/fonts/OpenSans-SemiboldItalic-webfont.woff +0 -0
  39. package/doc/api/global.html +1274 -0
  40. package/doc/api/index.html +236 -0
  41. package/doc/api/scripts/linenumber.js +34 -0
  42. package/doc/api/scripts/prettify/Apache-License-2.0.txt +202 -0
  43. package/doc/api/scripts/prettify/lang-css.js +2 -0
  44. package/doc/api/scripts/prettify/prettify.js +28 -0
  45. package/doc/api/styles/jsdoc-default.css +699 -0
  46. package/doc/api/styles/prettify-jsdoc.css +120 -0
  47. package/doc/api/styles/prettify-tomorrow.css +141 -0
  48. package/doc/json.min.visualization.html +4949 -0
  49. package/doc/json.visualization.html +4949 -0
  50. package/package.json +87 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,219 @@
1
+ # Enhanced JSON Parsing and Stringification for Large Numbers and Collections
2
+
3
+ [![npm package](https://img.shields.io/npm/v/@qubit-ltd/json.svg)](https://npmjs.com/package/@qubit-ltd/json)
4
+ [![License](https://img.shields.io/badge/License-Apache-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0)
5
+ [![中文文档](https://img.shields.io/badge/文档-中文版-blue.svg)](README.zh_CN.md)
6
+ [![CircleCI](https://dl.circleci.com/status-badge/img/gh/Haixing-Hu/js-json/tree/master.svg?style=shield)](https://dl.circleci.com/status-badge/redirect/gh/Haixing-Hu/js-json/tree/master)
7
+ [![Coverage Status](https://coveralls.io/repos/github/Haixing-Hu/js-json/badge.svg?branch=master)](https://coveralls.io/github/Haixing-Hu/js-json?branch=master)
8
+
9
+ [@qubit-ltd/json] is a JavaScript library that extends the functionality of the
10
+ standard JSON object, providing robust support for working with numbers that
11
+ exceed JavaScript’s safe range. It offers enhanced parsing and stringifying
12
+ capabilities, making it ideal for handling large datasets and complex numerical
13
+ operations while adhering to JSON’s structure.
14
+
15
+ ## Key Features
16
+
17
+ - `BigInt` Support: When parsing JSON strings, numbers outside JavaScript’s safe
18
+ integer range are automatically converted to the native `BigInt`, ensuring
19
+ precision is maintained.
20
+ - `LosslessNumber` Handling: For floating-point numbers that cannot be accurately
21
+ represented in JavaScript, this library introduces the `LosslessNumber` object.
22
+ This lightweight object preserves the full precision of the number as a string,
23
+ allowing flexible conversion to number or `BigInt` for mathematical operations.
24
+ - Accurate Stringification: During the stringify process, `BigInt` values are
25
+ serialized as strings without the “n” suffix, maintaining compatibility with
26
+ the standard JSON format. Similarly, `LosslessNumber` objects are serialized
27
+ using their internal string representation.
28
+ - Collection Serialization: JavaScript’s native collections like `Set` and `Map`
29
+ are seamlessly serialized as arrays, allowing for better compatibility with
30
+ JSON structures.
31
+
32
+ For more details on why JSON parsing can corrupt large numbers and how this
33
+ library helps resolve the issue, refer to
34
+ [Why does JSON.parse corrupt large numbers and how to solve this?].
35
+
36
+ ## Installation
37
+
38
+ To install the library, use either npm or yarn:
39
+ ```sh
40
+ npm install @qubit-ltd/json
41
+ ```
42
+ or
43
+ ```sh
44
+ yarn add @qubit-ltd/json
45
+ ```
46
+
47
+ ## Core Functionality
48
+
49
+ ### JSON-like Object
50
+
51
+ The library provides an object similar to the standard JSON object, but with
52
+ enhanced capabilities for handling large integers, floating-point numbers, and
53
+ collections like Set and Map.
54
+
55
+ ```javascript
56
+ import Json from '@qubit-ltd/json';
57
+
58
+ // parse numbers outside the safe range
59
+ const str1 = '{"decimal":2.370,"big_int":9123372036854000123,"big_float":2.3e+500}';
60
+ const obj1 = Json.parse(text);
61
+ console.log(obj1.decimal); // 2.37
62
+ console.log(obj1.big_int); // 9123372036854000123n
63
+ console.log(obj1.big_float); // LosslessNumber { value: '2.3e+500', isLosslessNumber: true }
64
+ console.log(String(obj1.big_float)); // '2.3e+500'
65
+
66
+ // stringify numbers outside the safe range
67
+ const json1 = Json.stringify(obj1);
68
+ console.log(json1); // '{"decimal":2.37,"big_int":9123372036854000123,"big_float":"2.3e+500"}'
69
+
70
+ // stringify collections
71
+ const obj2 = {
72
+ x: new Set([{ a: 1 }, { b: 2 }, { c: 3 }]),
73
+ y: new Map([[1, { a: 2 }], [2, { b: 4 }]]),
74
+ };
75
+ const json2 = Json.stringify(obj);
76
+ console.log(json2); // '{"x":[{"a":1},{"b":2},{"c":3}],"y":[[1,{"a":2}],[2,{"b":4}]]}'
77
+
78
+ const json3 = Json.stringify(obj, null, 2);
79
+ console.log(json3); //
80
+ ```
81
+
82
+ ### LosslessNumber Class
83
+
84
+ The LosslessNumber class is used to handle floating-point numbers with full
85
+ precision, avoiding truncation or rounding issues.
86
+
87
+ ```javascript
88
+ import Json from '@qubit-ltd/json';
89
+ const parsed = Json.parse('{"float": 1.234567891234567891234}');
90
+ console.log(parsed.float); // LosslessNumber { value: '1.234567891234567891234' }
91
+
92
+ // Convert LosslessNumber to standard number
93
+ console.log(parsed.float.valueOf()); // 1.2345678912345679 (standard JS number)
94
+ ```
95
+
96
+ ### Utility Functions
97
+
98
+ This library provides a set of utility functions to aid in the handling of large
99
+ numbers and ensure safe conversions.
100
+
101
+ #### `isBigInt(value)`
102
+
103
+ Checks if a string represents a `BigInt` (i.e., ends with an “n” suffix).
104
+
105
+ ```javascript
106
+ import { isBigInt } from '@qubit-ltd/json';
107
+
108
+ console.log(isBigInt('12345n')); // true
109
+ console.log(isBigInt('12345')); // false
110
+ ```
111
+
112
+ #### `isInteger(value)`
113
+
114
+ Checks if a string represents an integer.
115
+
116
+ ```javascript
117
+ import { isInteger } from '@qubit-ltd/json';
118
+
119
+ console.log(isInteger('12345')); // true
120
+ console.log(isInteger('123.45')); // false
121
+ ```
122
+
123
+ #### `isNumber(value)`
124
+
125
+ Checks if a string represents a number.
126
+
127
+ ```javascript
128
+ import { isNumber } from '@qubit-ltd/json';
129
+
130
+ console.log(isNumber('12345')); // true
131
+ console.log(isNumber('-123.45')); // true
132
+ console.log(isNumber('1.23e-11')); // true
133
+ console.log(isNumber('abc')); // false
134
+ ```
135
+
136
+ #### `isSafeNumber(value, options)`
137
+
138
+ Checks if a string represents a number within JavaScript’s safe range.
139
+
140
+ ```javascript
141
+ import { isSafeNumber } from '@qubit-ltd/json';
142
+
143
+ console.log(isSafeNumber('12345')); // true
144
+ console.log(isSafeNumber('12345678901234567890')); // false
145
+ console.log(isSafeNumber('123.45678901234567890')); // false
146
+ console.log(isSafeNumber('123.45678901234567890', { approx: true, requiredDigits: 16 })); // true
147
+ ```
148
+
149
+ #### `getUnsafeReason(value)`
150
+
151
+ Explains why a number represented by a string is unsafe, returning one of the
152
+ following reasons:
153
+
154
+ - `'overflow'`
155
+ - `'underflow'`
156
+ - `'truncate_integer'`
157
+ - `'truncate_float'`
158
+ - `'none'`: when the value is safe
159
+
160
+ ```javascript
161
+ import { getUnsafeReason } from '@qubit-ltd/json';
162
+
163
+ console.log(getUnsafeReason('12345')); // Output: 'none'
164
+ console.log(getUnsafeReason('12345678901234567890')); // Output: 'truncate_integer'
165
+ console.log(getUnsafeReason('-12345678901234567890.123')); // Output: 'truncate_float'
166
+ console.log(getUnsafeReason('-1e+1000')); // Output: 'overflow'
167
+ console.log(getUnsafeReason('1e-324')); // Output: 'underflow'
168
+ ```
169
+
170
+ #### `toSafeNumberOrThrow(value, options)`
171
+
172
+ Converts a string into a number if it is safe to do so. Throws an error if the
173
+ number is unsafe, explaining the reason.
174
+
175
+ ```javascript
176
+ import { toSafeNumberOrThrow } from '@qubit-ltd/json';
177
+
178
+ try {
179
+ console.log(toSafeNumberOrThrow('-12345678901234567890'));
180
+ } catch (e) {
181
+ console.error(e.message); // Output: 'Cannot safely convert to number: the value '-12345678901234567890' would truncate integer and become -12345678901234567000'
182
+ }
183
+
184
+ console.log(toSafeNumberOrThrow('9007199254740991')); // Output: 9007199254740991
185
+ ```
186
+
187
+ ## <span id="contributing">Contributing</span>
188
+
189
+ If you find any issues or have suggestions for improvements, please feel free
190
+ to open an issue or submit a pull request to the [GitHub repository].
191
+
192
+ ## <span id="license">License</span>
193
+
194
+ [@qubit-ltd/json] is distributed under the Apache 2.0 license.
195
+ See the [LICENSE](LICENSE) file for more details.
196
+
197
+ ## <span id="acknowledgements">Acknowledgements</span>
198
+
199
+ This project builds upon and incorporates code from several open-source libraries
200
+ that have made significant contributions to handling large numbers and custom
201
+ parsing in JSON. We would like to acknowledge and thank the authors of the
202
+ following projects:
203
+
204
+ - [json-bigint]: Provides support for parsing and stringifying JSON with BigInt,
205
+ allowing for precise handling of large numbers.
206
+ - [lossless-json]: A library that offers lossless handling of numbers in JSON,
207
+ ensuring full precision when dealing with floating-point values.
208
+ - [json-custom-numbers]: Allows for custom handling of numbers in JSON parsing
209
+ and stringifying, offering flexibility in numerical representation.
210
+
211
+ We are grateful for the work of these contributors, which has been instrumental
212
+ in shaping the functionality of this library.
213
+
214
+ [@qubit-ltd/json]: https://npmjs.com/package/@qubit-ltd/json
215
+ [GitHub repository]: https://github.com/Haixing-Hu/js-json
216
+ [Why does JSON.parse corrupt large numbers and how to solve this?]: https://jsoneditoronline.org/indepth/parse/why-does-json-parse-corrupt-large-numbers/
217
+ [json-bigint]: https://github.com/sidorares/json-bigint
218
+ [lossless-json]: https://github.com/josdejong/lossless-json
219
+ [json-custom-numbers]: https://github.com/jawj/json-custom-numbers
@@ -0,0 +1,194 @@
1
+ # 增强的 JSON 解析器,支持大整数和集合
2
+
3
+ [![npm package](https://img.shields.io/npm/v/@qubit-ltd/json.svg)](https://npmjs.com/package/@qubit-ltd/json)
4
+ [![License](https://img.shields.io/badge/License-Apache-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0)
5
+ [![English Document](https://img.shields.io/badge/Document-English-blue.svg)](README.md)
6
+ [![CircleCI](https://dl.circleci.com/status-badge/img/gh/Haixing-Hu/js-json/tree/master.svg?style=shield)](https://dl.circleci.com/status-badge/redirect/gh/Haixing-Hu/js-json/tree/master)
7
+ [![Coverage Status](https://coveralls.io/repos/github/Haixing-Hu/js-json/badge.svg?branch=master)](https://coveralls.io/github/Haixing-Hu/js-json?branch=master)
8
+
9
+ [@qubit-ltd/json] 是一个 JavaScript 库,它扩展了标准 JSON 对象的功能,提供了对超出 JavaScript
10
+ 安全范围的大数字的强大支持。该库增强了解析和字符串化能力,使其非常适合处理大型数据集和复杂的数值操作,
11
+ 同时保持 JSON 的结构。
12
+
13
+ ## 主要功能
14
+
15
+ - **`BigInt` 支持**:在解析 JSON 字符串时,超出 JavaScript 安全整数范围的数字会自动转换为原生 `BigInt`,
16
+ 确保精度不丢失。
17
+ - **`LosslessNumber` 处理**:对于无法在 JavaScript 中准确表示的浮点数,该库引入了 `LosslessNumber` 对象。
18
+ 这个轻量级对象以字符串形式保存完整的数值精度,允许灵活地转换为数字或 `BigInt` 进行数学运算。
19
+ - **精确的字符串化**:在字符串化过程中,`BigInt` 值会作为字符串序列化,不带 “n” 后缀,以保持与标准 JSON 格式的兼容性。
20
+ 同样,`LosslessNumber` 对象使用其内部字符串表示进行序列化。
21
+ - **集合序列化**:JavaScript 原生的集合类型如 `Set` 和 `Map` 会无缝地序列化为数组,以便更好地与 JSON 结构兼容。
22
+
23
+ 有关为什么 JSON 解析可能会破坏大数字以及该库如何帮助解决该问题的更多详细信息,请参阅
24
+ [Why does JSON.parse corrupt large numbers and how to solve this?]。
25
+
26
+ ## 安装
27
+
28
+ 使用 npm 或 yarn 安装该库:
29
+ ```sh
30
+ npm install @qubit-ltd/json
31
+ ```
32
+
33
+ ```sh
34
+ yarn add @qubit-ltd/json
35
+ ```
36
+
37
+ ## 核心功能
38
+
39
+ ### 类似 JSON 的对象
40
+
41
+ 该库提供了一个类似于标准 JSON 对象的对象,但具有增强的功能,用于处理大整数、浮点数以及集合类型如 Set 和 Map。
42
+
43
+ ```javascript
44
+ import Json from '@qubit-ltd/json';
45
+
46
+ // parse numbers outside the safe range
47
+ const str1 = '{"decimal":2.370,"big_int":9123372036854000123,"big_float":2.3e+500}';
48
+ const obj1 = Json.parse(text);
49
+ console.log(obj1.decimal); // 2.37
50
+ console.log(obj1.big_int); // 9123372036854000123n
51
+ console.log(obj1.big_float); // LosslessNumber { value: '2.3e+500', isLosslessNumber: true }
52
+ console.log(String(obj1.big_float)); // '2.3e+500'
53
+
54
+ // stringify numbers outside the safe range
55
+ const json1 = Json.stringify(obj1);
56
+ console.log(json1); // '{"decimal":2.37,"big_int":9123372036854000123,"big_float":"2.3e+500"}'
57
+
58
+ // stringify collections
59
+ const obj2 = {
60
+ x: new Set([{ a: 1 }, { b: 2 }, { c: 3 }]),
61
+ y: new Map([[1, { a: 2 }], [2, { b: 4 }]]),
62
+ };
63
+ const json2 = Json.stringify(obj);
64
+ console.log(json2); // '{"x":[{"a":1},{"b":2},{"c":3}],"y":[[1,{"a":2}],[2,{"b":4}]]}'
65
+
66
+ const json3 = Json.stringify(obj, null, 2);
67
+ console.log(json3); //
68
+ ```
69
+
70
+ ### LosslessNumber 类
71
+
72
+ `LosslessNumber` 类用于处理具有完整精度的浮点数,避免截断或舍入问题。
73
+
74
+ ```javascript
75
+ import Json from '@qubit-ltd/json';
76
+ const parsed = Json.parse('{"float": 1.234567891234567891234}');
77
+ console.log(parsed.float); // LosslessNumber { value: '1.234567891234567891234' }
78
+
79
+ // Convert LosslessNumber to standard number
80
+ console.log(parsed.float.valueOf()); // 1.2345678912345679 (standard JS number)
81
+ ```
82
+
83
+ ### 实用函数
84
+
85
+ 该库提供了一组实用函数,用于处理大数字并确保安全转换。
86
+
87
+ #### `isBigInt(value)`
88
+
89
+ 检查一个字符串是否表示 `BigInt`(即是否以 "n" 结尾)。
90
+
91
+ ```javascript
92
+ import { isBigInt } from '@qubit-ltd/json';
93
+
94
+ console.log(isBigInt('12345n')); // true
95
+ console.log(isBigInt('12345')); // false
96
+ ```
97
+
98
+ #### `isInteger(value)`
99
+
100
+ 检查一个字符串是否表示整数。
101
+
102
+ ```javascript
103
+ import { isInteger } from '@qubit-ltd/json';
104
+
105
+ console.log(isInteger('12345')); // true
106
+ console.log(isInteger('123.45')); // false
107
+ ```
108
+
109
+ #### `isNumber(value)`
110
+
111
+ 检查一个字符串是否表示数字。
112
+
113
+ ```javascript
114
+ import { isNumber } from '@qubit-ltd/json';
115
+
116
+ console.log(isNumber('12345')); // true
117
+ console.log(isNumber('-123.45')); // true
118
+ console.log(isNumber('1.23e-11')); // true
119
+ console.log(isNumber('abc')); // false
120
+ ```
121
+
122
+ #### `isSafeNumber(value, options)`
123
+
124
+ 检查一个字符串是否表示在 JavaScript 安全范围内的数字。
125
+
126
+ ```javascript
127
+ import { isSafeNumber } from '@qubit-ltd/json';
128
+
129
+ console.log(isSafeNumber('12345')); // true
130
+ console.log(isSafeNumber('12345678901234567890')); // false
131
+ console.log(isSafeNumber('123.45678901234567890')); // false
132
+ console.log(isSafeNumber('123.45678901234567890', { approx: true, requiredDigits: 16 })); // true
133
+ ```
134
+
135
+ #### `getUnsafeReason(value)`
136
+
137
+ 解释为什么由字符串表示的数字不安全,返回以下原因之一:
138
+
139
+ - `'overflow'`(溢出)
140
+ - `'underflow'`(下溢)
141
+ - `'truncate_integer'`(整数截断)
142
+ - `'truncate_float'`(浮点数截断)
143
+ - `'none'`:当值是安全时
144
+
145
+ ```javascript
146
+ import { getUnsafeReason } from '@qubit-ltd/json';
147
+
148
+ console.log(getUnsafeReason('12345')); // Output: 'none'
149
+ console.log(getUnsafeReason('12345678901234567890')); // Output: 'truncate_integer'
150
+ console.log(getUnsafeReason('-12345678901234567890.123')); // Output: 'truncate_float'
151
+ console.log(getUnsafeReason('-1e+1000')); // Output: 'overflow'
152
+ console.log(getUnsafeReason('1e-324')); // Output: 'underflow'
153
+ ```
154
+
155
+ #### `toSafeNumberOrThrow(value, options)`
156
+
157
+ 如果可以安全转换,将字符串转换为数字。如果数字不安全,则抛出错误并解释原因。
158
+
159
+ ```javascript
160
+ import { toSafeNumberOrThrow } from '@qubit-ltd/json';
161
+
162
+ try {
163
+ console.log(toSafeNumberOrThrow('-12345678901234567890'));
164
+ } catch (e) {
165
+ console.error(e.message); // Output: 'Cannot safely convert to number: the value '-12345678901234567890' would truncate integer and become -12345678901234567000'
166
+ }
167
+
168
+ console.log(toSafeNumberOrThrow('9007199254740991')); // Output: 9007199254740991
169
+ ```
170
+
171
+ ## <span id="contributing">贡献</span>
172
+
173
+ 如果您发现任何问题或有改进建议,请随时在 [GitHub 仓库] 上提交 issue 或 pull request。
174
+
175
+ ## <span id="license">许可证</span>
176
+
177
+ [@qubit-ltd/json] 根据 Apache 2.0 许可证分发。详情请参阅 [LICENSE](LICENSE) 文件。
178
+
179
+ ## <span id="acknowledgements">致谢</span>
180
+
181
+ 该项目基于并集成了多个开源库的代码,这些库在处理大数字和自定义 JSON 解析方面做出了重要贡献。我们想特别感谢以下项目的作者:
182
+
183
+ - [json-bigint]:提供对使用 BigInt 解析和字符串化 JSON 的支持,使得可以精确处理大数字。
184
+ - [lossless-json]:一个确保在处理浮点数时保持完全精度的库,提供无损的 JSON 数字处理。
185
+ - [json-custom-numbers]:允许在 JSON 解析和字符串化过程中自定义数字处理,提供灵活的数值表示。
186
+
187
+ 我们对这些贡献者的工作表示感谢,这些工作对本库功能的实现起到了至关重要的作用。
188
+
189
+ [@qubit-ltd/json]: https://npmjs.com/package/@qubit-ltd/json
190
+ [GitHub repository]: https://github.com/Haixing-Hu/js-json
191
+ [Why does JSON.parse corrupt large numbers and how to solve this?]: https://jsoneditoronline.org/indepth/parse/why-does-json-parse-corrupt-large-numbers/
192
+ [json-bigint]: https://github.com/sidorares/json-bigint
193
+ [lossless-json]: https://github.com/josdejong/lossless-json
194
+ [json-custom-numbers]: https://github.com/jawj/json-custom-numbers