JsonTools Notepad++ Plugin

repository·main·Indexed 41 days ago

https://github.com/molsonkiko/jsontoolsnppplugin

A collection of tools for working with JSON in Notepad++, featuring a hierarchical tree viewer, advanced parsing for JSON5 and comments, and the ability to compress or pretty-print documents. It includes support for JSON Lines, INI files, and RemesPath queries for searching and mutating text, as well as a Sort form for managing arrays.

Tokens
24.7K
Snippets
68
Records
130
Agent score
52%

What's inside JsonTools

  1. Overview of JsonToolsNppPlugin features

    main

    JsonToolsNppPlugin provides a suite of tools for working with JSON within Notepad++:

    • Formatting: Pretty-print JSON (multi-line) and Compress JSON (minimal whitespace).
    • Navigation: A drop-down tree view where selecting a node navigates to the corresponding line in the document.
    • Robust Parsing: Supports JSON5, Python-style comments, missing commas/colons, and unterminated structures.
    • Querying & Editing:
      • Find/replace form
      • Array sorting form
      • RemesPath query language
      • Regex search form (for CSV or math-based find/replace)
    • Data Management: Parse JSON Lines, fetch JSON from APIs or local files, and generate random JSON from a schema.
    • Validation: JSON schema validation (including automatic validation based on filenames).
    • Utilities: Automatic error checking after editing, selecting JSON within non-JSON files, and converting between JSON strings and raw text.
  2. Use boolean indexing to filter arrays and objects

    main

    Boolean indexing allows you to select elements from an iterable (array or object) that satisfy a specific condition. The syntax uses the @ symbol to represent the current context.

    Filtering Arrays

    When applying a boolean index to an array, you can use a single boolean or an array of booleans of the same length.

    • Single Boolean: If the condition is true, the whole array is returned. If false, an empty array [] is returned.
    • Boolean Array: An array of booleans where each element corresponds to the index of the original array. Only elements where the boolean is true are kept.

    Filtering Objects

    When applying a boolean index to an object, you use an object of booleans with the exact same keys as the original object. Only the key-value pairs where the boolean value is true are kept.

    Version Note (v5.5.0+)

    Starting in v5.5.0, boolean indices can be applied to non-iterables (scalars) and one-boolean indices on objects return the original object instead of an array, allowing for further querying.

    // Array filtering with boolean array
    // Input: [1, 2, 3]
    @[@ > @[0]] // Returns [2, 3]
    
    // Object filtering
    // Input: {"a": 1, "b": 2, "c": 3}
    @[@ > @.a] // Returns {"b": 2, "c": 3}
  3. Regex behavior in s_sub

    main

    When using s_sub for regular expression replacements:

    1. Line Anchors: ^ and $ match the start and end of lines, not the start and end of the entire string.
    2. Numeric Matching:
      • (INT) matches integers.
      • (NUMBER) matches floating point decimals.
      • (?:INT) and (?:NUMBER) are the non-capturing versions of these expressions.
  4. How plugin architecture works

    main

    The plugin pack provides abstraction layers to make interacting with Notepad++ and the Scintilla engine easier and more testable.

    • NotepadPlusPlusGateway: A thin layer for interacting with the Notepad++ application.
    • ScintillaGateway: A thin layer for interacting with the underlying Scintilla editing engine.
    • Win32: Provides low-level access to the Win32 API.

    Your Plugin class sits above these gateways, allowing you to command the editor or the application through structured interfaces rather than raw API calls.

  5. Manage tree view performance and display

    main

    The JSON tree view is designed to be responsive by loading nodes on-demand. For very large files, the plugin may limit the initial view to prevent Notepad++ from becoming unresponsive.

    Large Array/Object Handling

    If an array or object has more than 10,000 direct children (configurable via Settings->max_json_length_full_tree), the plugin automatically displays 10,000 evenly spaced children as pointers to maintain performance.

    Toggling Full Tree View

    You can use the View all subtrees checkbox on the JSON viewer form to toggle between viewing the full tree and only the direct children of the root.

    • Warning: Checking this box for documents larger than 2.5 MB will trigger a warning, as loading the full tree for large documents can cause Notepad++ to become unresponsive for a long time.
    • Scope: This checkbox only affects the current tree view and does not change global settings.
  6. Query JSON using RemesPath

    main

    The primary way to interact with JSON in the plugin is via RemesPath.

    Usage:

    • Enter RemesPath queries into the textbox above the JSON tree viewer (which contains the @ symbol by default).
    • Submitting a query filters the tree view to the results.
    • You can open the query results in a new buffer.
    • History: Since v8.5.1, you can use the "Get recent RemesPath queries" command to review up to 16 past queries stored as a JSON array.
    Query input: `@` (default symbol in tree view textbox)
  7. Understand vectorized operations in RemesPath

    main

    Vectorized operations allow functions to operate on entire arrays or objects. When a function is called on an array or object, the first argument typically references each individual element (or child) separately, while subsequent arguments can reference the entire collection.

    Example: String multiplication s_mul(s, n) s_mul concatenates string s, n times.

    • With Array input ["a", "cd", "b"]: s_mul(@, len(@)) returns ["aaa", "cdcdcd", "bbb"].

      • The first argument @ refers to each element ("a", then "cd", etc.).
      • The second argument len(@) refers to the length of the entire array (3).
    • With Object input {"foo": "a", "bar": "cd"} (Requires v7.0+): s_mul(@, len(@)) returns {"foo": "aa", "bar": "cdcd"}.

      • The first argument @ refers to each value ("a", then "cd").
      • The second argument len(@) refers to the number of children in the object (2).
    // Array example
    s_mul(["a", "cd", "b"], len(@)) // returns ["aaa", "cdcdcd", "bbb"]
    
    // Object example (v7.0+)
    s_mul({"foo": "a", "bar": "cd"}, len(@)) // returns {"foo": "aa", "bar": "cdcd"}
  8. Special regex placeholders in s_fa

    main

    The s_fa function supports special placeholders within the regex pattern pat to simplify matching common types:

    • (INT): Matches a decimal number or a hex integer (preceded by 0x), optionally with a + or -. Use (?:INT) for a non-capturing version.
    • (NUMBER): Matches a decimal floating point number or a hex integer. Use (?:NUMBER) for a non-capturing version. Note: Neither matches NaN or Infinity.

    Important Notes:

    • s_fa treats ^ as the beginning of a line and $ as the end of a line (unlike other JsonTools functions where they match the start/end of the entire string).
    • s_fa may be slower if pat is a function of input, as regex transformations are applied on every call.
  9. Use logical functions with conditional execution

    main

    RemesPath provides and() and or() functions (added in v7.0) that support conditional execution. This is different from the binary & and | operators because they prevent unnecessary or potentially error-inducing evaluations.

    • and(x, y, ...): Returns true if and only if all arguments are "truthy". If an argument evaluates to false, subsequent arguments are not evaluated.
    • or(x, y, ...): Returns true if any argument is "truthy". If an argument evaluates to true, subsequent arguments are not evaluated.

    Example of conditional execution: If you check and(is_num(@), @ < 3), the expression @ < 3 will only be evaluated if is_num(@) is true. This prevents errors when @ is not a number.

    // Conditional execution example
    and(is_num(@), @ < 3)
  10. Work with JSON Lines (.jsonl) documents

    main

    JSON Lines documents contain multiple valid JSON documents, each on its own line. The plugin automatically parses files with the .jsonl extension as JSON Lines.

    Rules for valid JSON Lines:

    • Each document must be on exactly one line.
    • No empty lines are allowed between documents (though an optional empty line after the last document is fine).
    • One document cannot span multiple lines.

    Operations:

    • Conversion: Use the Array to JSON Lines command (v3.3.0+) to convert a standard JSON array into a JSON Lines document.
    • Manual Parsing: If a file lacks the .jsonl extension, use Plugins->JsonTools->Parse JSON Lines document.
    • Formatting: Since pretty-printing usually invalidates JSON Lines, the plugin (v5.8+) will prompt for confirmation before pretty-printing a .jsonl file. RemesPath edits will preserve the JSON Lines format.
  11. How JsonTools handles language translation

    main

    JsonTools (v8.0+) supports localization by automatically detecting the user's preferred language from the Notepad++ configuration.

    Translation Workflow:

    1. Detection: JsonTools checks the Notepad++ nativeLang.xml config file (XPath: /NotepadPlus/Native-Langue/@name) to find the lowerEnglishName (e.g., galician).
    2. Lookup: It searches the translation subdirectory within the JsonTools plugin folder for a file named {lowerEnglishName}.json5 (e.g., galician.json5).
    3. Fallback: If no file is found or parsing fails, it defaults to English.

    Important Notes:

    • Notepad++ Version: Translation requires Notepad++ version 8 or newer to support separate plugin subdirectories.
    • Lifecycle: Translation is only attempted once during Notepad++ startup. If you change the Notepad++ UI language, you must restart Notepad++ for JsonTools to update.
    • Disabling: To force English while keeping a specific Notepad++ language, append _disabled to the translation filename (e.g., german_disabled.json5).
  12. Understand string sorting behavior in JsonTools

    main

    JsonTools uses a sorting logic similar to Windows applications (like Microsoft Word), which differs from Notepad++'s Unicode code point-based sorting.

    Case-Sensitive Sorters

    The following features use case-sensitive sorting:

    • sorted and sort_by RemesPath functions.
    • The sort form when Sort method is set to Default.
    • Other RemesPath functions that perform sorting (unless otherwise specified).

    Case-Insensitive Sorters

    The following features use case-insensitive sorting:

    • Object key sorting when the sort_keys global setting is true.
    • Object key sorting when the sort_keys argument to the stringify RemesPath function is true.
    • The sort form when Sort method is set to As strings (ignoring case).

    Key Differences from Notepad++

    1. Numbers: The JsonTools sort form ignores leading minus signs when ordering numbers; Notepad++ does not.
    2. Non-ASCII Characters: JsonTools orders characters like ö culturally (e.g., between o and p), whereas Notepad++ places them at the end based on Unicode code points.
    3. Case Order: In case-sensitive mode, JsonTools places uppercase letters after lowercase letters. Notepad++ does the opposite.
    4. Alphabetical Respect: JsonTools respects alphabetical order (e.g., P follows o), while Notepad++ groups all uppercase letters before all lowercase letters in case-sensitive mode.