molsonkiko / JsonToolsNppPlugin

A Notepad++ plugin providing tools for JSON like linting, querying, a tree view, and CSV conversion.
Apache License 2.0
70 stars 9 forks source link

How to pretty-print/compress everything that satisfies condition X #61

Open molsonkiko opened 2 months ago

molsonkiko commented 2 months ago

Some people have raised issues (#39, #58) that reference the same basic issue: how do you pretty-print JSON while compressing all children that satisfy condition X. This could mean things like:

  1. I want to pretty-print my file, but compress the values associated with key foo
  2. I want to compress my file, but pretty-print every array with length less than 4

and so forth.

If you want something like that, do not raise an issue, and instead read this tutorial. I will close any issue that I think looks like that, because I do not feel like adding and maintaining features that might satisfy such requests, especially when a perfectly adequate solution already exists.

Many problems of this form can be solved using JsonTools, but you need to use RemesPath. Here's how:

  1. Pretty-print or compress your document according to how you want to format things that do not satisfy condition X.
  2. Open the tree view.
  3. Use RemesPath to match everything that satisfies condition X. You can check the tree view to make sure your query does what you want.
  4. Right-click the root tree node, and choose the Select all children option from the drop-down menu that appears.
  5. Choose the Pretty-print current JSON file or Compress current JSON file option to format only the JSON that is currently selected.
  6. The JSON that satisfy condition X is now formatted differently from the rest of the file.

Worked Example

Suppose you have the following JSON:

[{"bar":["rkS","O7/xt","c|-0%\\+","yfu3[?hMm\t","Miqj","0I"],"baz":{"ghk":false,"quz":0.99280108976774},"foo":545590},{"bar":["H/","P6t++\"!","G","","x)","2?","_;M[+O\nm","~C","h4V8d#","{m(@"],"baz":{"ghk":false,"quz":517435},"foo":-560427},{"bar":["{","U{hz\"","?/S","ON'","Sp","#pUXW{Ti~}","\tsnbuH<","\n&};t\\["],"baz":{"ghk":true,"quz":-2.93493113384346},"foo":-695227}]

and you want to pretty-print the document, but compress all the arrays with length less than 10 that are children of the bar key.

You would follow these steps:

  1. Pretty-print the document.
  2. Open the JSON tree view.
  3. Select the arrays that are children of the bar key with length less than 10 using the query @[:].bar[and(type(@) == array, len(@) < 10)] image
  4. Right-click the root tree node, then click Select all children option from the drop-down. image
  5. The arrays that satisfy condition X are now selected, as shown below. image
  6. Run the Compress current JSON file command, and the arrays that satisfy condition X will be compressed without affecting the rest of the document. image