我希望从输入字符串中获得json键的位置(起始偏移量)。
例如,我想检索键-1的位置:
{
"entity" : {
"key-1" : "a",
"key-2" : "b"
}
}`;我尝试过许多不同的方法,但有一个最接近的方法:
function getOffset(path:string)
{
let testData = `
{
"entity" : {
"key-1" : "a",
"key-2" : "b"
}
}`;
let jsonMap = require('json-source-map');
let stringify = jsonMap.stringify(JSON.parse((testData)));
console.log(stringify);
let pointer = stringify.pointers[path];
return pointer.key;
}
export function CheckSyntax(editor:vscode.TextEditor)
{
let key = getOffset("/entity/key-1");
console.log(key);
}问题是字符串被转换为对象,并松散了有关原始字符串( testData )的所有引用。所以我有一个偏移量,但是它相对于一个新的jsonString。
注意:使用find并不能达到目的,因为会有许多具有相同子键名的对象。
注之二:最后一个目标是在进行一些内部检查后突出显示一个错误的键。
发布于 2019-10-04 12:38:04
参见.stringify文档中的示例。如果你去掉无用的绞线:
var jsonMap = require('json-source-map');
CheckSyntax(`{
"entity" : {
"key-1" : "a",
"key-2" : "b"
}
}`);
function getOffset(path)
{
let testData = `
{
"entity" : {
"key-1" : "a",
"key-2" : "b"
}
}`;
let jsonMap = require('json-source-map');
let stringify = jsonMap.parse(testData);
console.log(JSON.stringify(stringify, null, 2));
let pointer = stringify.pointers[path];
return pointer.key;
}
function CheckSyntax(editor)
{
let key = getOffset("/entity/key-1");
console.log(key);
}并获得您想要的结果(键和字符串输出切换):
null: Object {line: 3, column: 12, pos: 41}
{
"data": {
"entity": {
"key-1": "a",
"key-2": "b"
}
},
"pointers": {
"": {
"value": {
"line": 1,
"column": 4,
"pos": 5
},
"valueEnd": {
"line": 6,
"column": 5,
"pos": 97
}
},
"/entity": {
"key": {
"line": 2,
"column": 8,
"pos": 16
},
"keyEnd": {
"line": 2,
"column": 16,
"pos": 24
},
"value": {
"line": 2,
"column": 19,
"pos": 27
},
"valueEnd": {
"line": 5,
"column": 9,
"pos": 91
}
},
"/entity/key-1": {
"key": {
"line": 3,
"column": 12,
"pos": 41
},
"keyEnd": {
"line": 3,
"column": 19,
"pos": 48
},
"value": {
"line": 3,
"column": 22,
"pos": 51
},
"valueEnd": {
"line": 3,
"column": 25,
"pos": 54
}
},
"/entity/key-2": {
"key": {
"line": 4,
"column": 12,
"pos": 68
},
"keyEnd": {
"line": 4,
"column": 19,
"pos": 75
},
"value": {
"line": 4,
"column": 22,
"pos": 78
},
"valueEnd": {
"line": 4,
"column": 25,
"pos": 81
}
}
}
}https://stackoverflow.com/questions/58219642
复制相似问题