ace - Does JSONEditor have a default function to get the JSON block from the cursor position? - Stack Overflow

时间: 2025-01-06 admin 业界

We are using jsonEDITOR to process JSON data. Ace do have default feature to track opening and closing of { and ] of jsonBlock. see screenshot. any way we can extract those content? I am trying to get the below JSON value:

 {
      "array": [
        1,
        2,
        3
      ],
      "boolean": true,
      "color": "gold",
      "null": null,
      "number": 123,
      "object": {
        "a": "b",
        "c": "d"
      },
      "string": "Hello World"
    }

We are using jsonEDITOR to process JSON data. Ace do have default feature to track opening and closing of { and ] of jsonBlock. see screenshot. any way we can extract those content? I am trying to get the below JSON value:

 {
      "array": [
        1,
        2,
        3
      ],
      "boolean": true,
      "color": "gold",
      "null": null,
      "number": 123,
      "object": {
        "a": "b",
        "c": "d"
      },
      "string": "Hello World"
    }
Share Improve this question asked yesterday Sushil AdhikariSushil Adhikari 7947 silver badges13 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JSONEditor Cursor Example (Code Mode)</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/9.10.0/jsoneditor.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/9.10.0/jsoneditor.min.css">
  <style>
    #jsoneditor { width: 100%; height: 400px; }
    #result { margin-top: 20px; font-family: monospace; white-space: pre-wrap; }
  </style>
</head>
<body>

  <h1>JSONEditor Cursor Example (Code Mode)</h1>
  <div id="jsoneditor"></div>
  <button onclick="getJSONBlockAtCursor()">Get JSON Block at Cursor</button>
  <div id="result"></div>

  <script>
    // Initialize JSONEditor in 'code' mode
    const container = document.getElementById('jsoneditor');
    const options = {
      mode: 'code'
    };
    const editor = new JSONEditor(container, options);

    // Sample JSON
    const initialJson = {
      "name": "John",
      "age": 30,
      "address": {
        "street": "123 Main St",
        "city": "New York"
      },
      "hobbies": ["reading", "cycling"]
    };
    editor.set(initialJson);

    // Function to get JSON Block at Cursor
    function getJSONBlockAtCursor() {
      try {
        // Access the Ace Editor instance from JSONEditor
        const aceEditor = editor.aceEditor;
        if (!aceEditor) {
          document.getElementById('result').innerText = 'Ace Editor instance not found.';
          return;
        }

        // Get the cursor position
        const cursor = aceEditor.getCursorPosition();

        // Use Ace Editor's range API to expand selection to the surrounding JSON block
        const session = aceEditor.getSession();
        const Range = ace.require('ace/range').Range;
        // this is to switch to column one space backyard so we can get valid json block
        cursor.column = cursor.column - 1

        let range = session.getBracketRange(cursor);
        if (!range) {
          document.getElementById('result').innerText = 'No valid JSON block detected at cursor.';
          return;
        }

        // Extract text from the range
        const blockText = session.getTextRange(range).trim();
        console.log(blockText)

        // Validate and parse the JSON block
        let jsonBlock;
        try {
          jsonBlock = JSON.parse(blockText);
        } catch (e) {
          document.getElementById('result').innerText = 'Invalid JSON block detected.';
          return;
        }

        document.getElementById('result').innerText = `JSON Block:\n${JSON.stringify(jsonBlock, null, 2)}`;
      } catch (error) {
        document.getElementById('result').innerText = 'Error: ' + error.message;
      }
    }
  </script>
</body>
</html>

Copy the above content on index.html and open on your own browser. It will give you selected node