parse-part-json
Version:
Can parse an incomplete JSON string
122 lines (94 loc) • 2.72 kB
Markdown
# parse-part-json
This is a library that can parse incomplete JSON
## Installation
```bash
$ npm i parse-part-json
```
## Demo
ESModule:
```js
import { parsePartJson } from 'parse-part-json'
```
Commonjs:
```js
const { parsePartJson } = require('parse-part-json')
```
Example:
```js
/**
* note: This is not a complete JSON
*/
const json1 = `{"name": "John", "age": 30`
const result1 = parsePartJson(json1)
console.log(result1) // { name: 'John', age: 30 }
/**
* Default tolerance for incomplete parsing of basic types
*/
const json2 = `{"name": "John", "age":nu`
const result2 = parsePartJson(json2)
console.log(result2) // { name: 'John', age: null }
// this throw BasicParseIncomplete Error
const result3 = parsePartJson(json2, { tolerateBasicIncomplete: false })
```
## Preview
https://parse-part-json-demo.vercel.app/
## Speed compare
The functionality of the **`partial-json`** library is the same as that of the **`parse-part-json`** library. Based on my terminal testing and comparison, their JSON parsing speeds vary depending on the data type, but in most cases, **`parse-part-json`** is 20–30% faster than **`partial-json`**.
```js
import { parse } from 'partial-json'
import { parsePartJson } from 'parse-part-json'
const json1 = `{
"appName": "WeatherTracker",
"version": "1.2.0",
"features": ["forecast", "alerts", "maps"],
"settings": {
"units": "metric",
"language": "en",
"notifications": true
},
"sampleData": {
"cities": [
{
"id": 1001,
"name": "Springfield",
"temperature": 22.5,
"conditions": "partly cloudy"
},
{
"id": 1002,
"name": "Shelbyville",
"temperature": 19.8,
"conditions": "sunny"
}
],
"updateTimestamp": "2023-05-16T14:30:00Z"
},
"metadata": {
"developer": "Acme Apps",
"releaseYear": 2023,
"supportedOS": ["Android", "iOS", "`
// tset result:true
console.log(
JSON.stringify(parse(json1)) === JSON.stringify(parsePartJson(json1))
)
//test speed
let start = Date.now()
for (let i = 0; i < 100000; i++) {
parse(json1)
}
let end = Date.now()
// parse: 6023ms
console.log(`parse: ${end - start}ms`)
let start2 = Date.now()
for (let i = 0; i < 100000; i++) {
parsePartJson(json1)
}
let end2 = Date.now()
// parsePartJson: 1259ms
console.log(`parsePartJson: ${end2 - start2}ms`)
```
##### The time consumed for parsing 100000 times in the same JSON segment (note: the results may vary depending on the device):
parse-part-json : 1259ms
partial-json : 6023ms
## Support
ESModule、Commonjs