解析json
使用更多有用的错误解析JSON
安装
npm install parse-json
用法
import parseJson, {JSONError} from 'parse-json';
const json = '{\n\t"foo": true,\n}';
JSON.parse(json);
/*
SyntaxError: Expected double-quoted property name in JSON at position 16 (line 3 column 1)
*/
parseJson(json);
/*
JSONError: Expected double-quoted property name in JSON at position 16 (line 3 column 1)
1 | {
2 | "foo": true,
> 3 | }
| ^
*/
parseJson(json, 'foo.json');
/*
JSONError: Expected double-quoted property name in JSON at position 16 (line 3 column 1) in foo.json
1 | {
2 | "foo": true,
> 3 | }
| ^
fileName: 'foo.json',
[cause]: SyntaxError: Expected double-quoted property name in JSON at position 16 (line 3 column 1)
at JSON.parse (<anonymous>)
at ...
*/
// You can also add the filename at a later point
try {
parseJson(json);
} catch (error) {
if (error instanceof JSONError) {
error.fileName = 'foo.json';
}
throw error;
}
/*
JSONError: Expected double-quoted property name in JSON at position 16 (line 3 column 1) in foo.json
1 | {
2 | "foo": true,
> 3 | }
| ^
fileName: 'foo.json',
[cause]: SyntaxError: Expected double-quoted property name in JSON at position 16 (line 3 column 1)
at JSON.parse (<anonymous>)
at ...
*/
API
parseJson(字符串,兴奋剂?,文件名?)
抛出一个 JSONError 当出现解析错误时。
字符串
类型: string
兴奋剂
类型: Function
规定在返回之前如何转换解析最初产生的值。看到 JSON.parse 文档 更多信息。
文件名
类型: string
错误消息中显示的文件名。
JSONError
暴露在 instanceof 检查。
文件名
类型: string
错误消息中显示的文件名。
codeFrame
类型: string
JSON中产生错误的可打印部分。
rawCodeFrame
类型: string
原始版本的 codeFrame 没有颜色。