【发布时间】:2021-09-10 12:22:53
【问题描述】:
我正在创建一个 typescript 库来针对一些自定义约束验证 JSON 文件,例如我有这个 json 文件:
[
{
"nodes": [
{
"id": 1,
"name": "node 1"
},
{
"id": 1, // <--- here needs to throw an error because of duplicate ids
"name": "node 2"
}
],
"edges": [
{
"id": 1,
"nodeId": 1,
"name": "edge 1"
},
{
"id": 2,
"nodeId": 3, // <--- here needs to throw an error because of node id does not exist
"name": "edge 1"
}
]
}
]
我已经在使用 json shcema 来验证 json 的结构(例如 required 属性、类型...)。
使用打字稿,我可以轻松地循环抛出 2 个列表并找到错误,但问题是我无法获取该错误的位置(line 和column)所以有没有办法获取行号我的错误?如果不可能,还有其他方法可以为用户返回有用的错误吗?
【问题讨论】:
-
API of node-jsonc-parser 看起来很有前途。或者json-to-ast 可能会起作用,但是您必须处理 AST 输出,这可能相当麻烦。
标签: javascript json typescript