开源项目 parse-json
使用教程
parse-jsonParse JSON with more helpful errors项目地址:https://gitcode.com/gh_mirrors/pa/parse-json
1. 项目的目录结构及介绍
parse-json/
├── index.js
├── license
├── package.json
├── readme.md
└── test.js
index.js
: 项目的主文件,包含解析JSON的主要逻辑。license
: 项目的许可证文件。package.json
: 项目的配置文件,包含依赖、脚本等信息。readme.md
: 项目的说明文档。test.js
: 项目的测试文件。
2. 项目的启动文件介绍
index.js
是项目的启动文件,主要功能是解析JSON字符串。以下是文件的主要内容:
'use strict';
const errorEx = require('error-ex');
const fallback = require('json-parse-even-better-errors');
const linesAndColumns = require('lines-and-columns').default;
const isErrorConstructor = require('is-error-constructor');
const JSONError = errorEx('JSONError', {
fileName: errorEx.append('in %s'),
codeFrame: errorEx.append('\n\n%s\n')
});
module.exports = (json, reviver, fileName) => {
if (typeof reviver === 'string') {
fileName = reviver;
reviver = undefined;
}
try {
try {
return JSON.parse(json, reviver);
} catch (error) {
if (process.env.NODE_ENV === 'development') {
if (isErrorConstructor(error.constructor)) {
throw error;
}
const lines = new linesAndColumns(json);
const index = error.message.indexOf(' at ');
const locationString = error.message.slice(index + 4);
const location = lines.locationForIndex(index === -1 ? 0 : index);
error.message = error.message.slice(0, index === -1 ? error.message.length : index);
error.message = ` in JSON at position ${location.index} ${locationString}`;
error.fileName = fileName;
error.codeFrame = generateCodeFrame(json, location.line, location.column);
throw new JSONError(error);
}
return fallback(json, reviver);
}
} catch (error) {
error.fileName = fileName;
throw error;
}
};
function generateCodeFrame(json, line, column) {
const lines = json.split('\n');
const maxWidth = String(line + 1).length;
const frameLines = [];
for (let i = line - 2; i <= line; i++) {
if (i + 1 === line) {
frameLines.push(`${i + 1} | ${lines[i]}`);
frameLines.push(`${' '.repeat(maxWidth)} | ${' '.repeat(column)}^`);
} else if (lines[i]) {
frameLines.push(`${i + 1} | ${lines[i]}`);
}
}
return frameLines.join('\n');
}
3. 项目的配置文件介绍
package.json
是项目的配置文件,包含项目的基本信息、依赖、脚本等。以下是文件的主要内容:
{
"name": "parse-json",
"version": "5.2.0",
"description": "Parse JSON with more helpful errors",
"license": "MIT",
"repository": "sindresorhus/parse-json",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=8"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js"
],
"keywords": [
"json",
"parse",
"parser",
"reviver",
"error",
parse-jsonParse JSON with more helpful errors项目地址:https://gitcode.com/gh_mirrors/pa/parse-json