VSCode扩展开发:如何获取光标所在的JSON特定作用域信息?
Check if Cursor is Inside a JSON Array (Without AST/Language Services)
Since we can’t leverage VS Code’s built-in JSON AST or language services here, we can manually parse the text up to the cursor position to track our depth inside JSON arrays. This involves monitoring string context (to ignore brackets within string values) and counting array openings/closings as we go.
Here’s a practical implementation:
import * as vscode from 'vscode'; function isCursorInsideJsonArray(): boolean { const editor = vscode.window.activeTextEditor; if (!editor) { return false; // No active editor to work with } const document = editor.document; if (document.languageId !== 'json') { return false; // Skip non-JSON documents } const cursorPosition = editor.selection.start; const fullText = document.getText(); let inString = false; let arrayDepth = 0; // Iterate through every character before the cursor for (let i = 0; i < cursorPosition.character; i++) { const currentChar = fullText[i]; // Toggle string context (ignore escaped quotes) if (currentChar === '"') { let isEscaped = false; let j = i - 1; // Count consecutive backslashes to check if the quote is escaped while (j >= 0 && fullText[j] === '\\') { isEscaped = !isEscaped; j--; } if (!isEscaped) { inString = !inString; } } // Only process array brackets if we're not inside a string if (!inString) { if (currentChar === '[') { arrayDepth++; } else if (currentChar === ']') { // Avoid negative depth for invalid JSON (e.g., unclosed brackets) if (arrayDepth > 0) { arrayDepth--; } } } } // Positive depth means we're inside at least one array return arrayDepth > 0; }
How This Works:
- String Context Tracking: We flip an
inStringflag whenever we hit an unescaped double quote. This ensures brackets inside string values (like"example [text]") don’t interfere with our array depth count. - Array Depth Counting: For each unquoted
[, we increase the depth; for each unquoted], we decrease it (with a guard to prevent negative depth for malformed JSON). - Final Check: If the depth is greater than 0 after processing all characters up to the cursor, the cursor is inside one or more nested JSON arrays.
Edge Cases Handled:
- Brackets embedded within JSON strings
- Escaped quotes (e.g.,
"He said \"hi\"") that shouldn’t toggle string context - Invalid JSON with unbalanced brackets (gracefully avoids negative depth values)
内容的提问来源于stack exchange,提问作者philk
相关产品推荐
相关产品推荐

