What is destr?
The `destr` npm package is designed to safely parse JSON strings without throwing an error for invalid JSON. It can return the original string if parsing fails, making it useful for handling dynamic JSON data that may not always be properly formatted. It also recognizes and correctly parses values like `null`, `true`, `false`, and `undefined`.
What are destr's main functionalities?
Safe JSON parsing
Safely parse a JSON string without throwing an error. If the string is not valid JSON, it returns the original string.
"const destr = require('destr');
const json = '{\"key\":\"value\"}';
const parsed = destr(json);
console.log(parsed); // Output: { key: 'value' }"
Parsing special JSON values
Correctly parse special JSON values such as `null`, `true`, `false`, and `undefined`, returning their corresponding JavaScript types.
"const destr = require('destr');
console.log(destr('null')); // Output: null
console.log(destr('true')); // Output: true
console.log(destr('false')); // Output: false
console.log(destr('undefined')); // Output: undefined"
Other packages similar to destr
json5
Similar to `destr`, `json5` allows for parsing of JSON data with more lenient syntax rules, such as trailing commas and comments. However, `json5` focuses on extending JSON syntax to be more flexible, while `destr` focuses on safe parsing and handling special values.
safe-json-parse
This package offers functionality similar to `destr` by providing a safe way to parse JSON strings without throwing errors for invalid JSON. The main difference is in the API and specific handling of non-JSON values.
destr
A faster, secure and convenient alternative for JSON.parse
:
Fast fallback to input if is not string:
JSON.parse()
destr()
JSON.parse(3.14159265359)
destr(3.14159265359)
Fast lookup for known string values:
JSON.parse('TRUE')
destr('TRUE')
JSON.parse('true')
destr('true')
Fallback to original value if parse fails (empty or any plain string):
JSON.parse('salam')
destr('salam')
Avoid Prototype Pollution:
const input = '{ "user": { "__proto__": { "isAdmin": true } } }'
JSON.parse(input)
destr(input)
Better types:
interface JSON {
parse(text: string, reviver?: (this: any, key: string, value: any) => any): any
}
export declare type JSONObject = {
[key: string]: JSONValue;
};
export declare type JSONValue = true | false | null | string | JSONObject | JSONValue[];
export declare type DestrValue = JSONValue | JSONValue[] | undefined;
export default function destr(val: any): DestrValue;
License
MIT