musikinformatik / JSONlib

A JSON de- and encoder for SuperCollider
GNU General Public License v2.0
11 stars 0 forks source link

Add pretty printing string representation #30

Open capital-G opened 1 year ago

capital-G commented 1 year ago

@LFSaw suggested that having a pretty printer for the object to string method would be nice and I agree - I used vscode multiple times to make the JSON look more convenient during debugging, and after all, JSON is a human readable format and its reference implementation in JavaScript also offers this feature natively.

Examples

I looked up the JS and the Python implementation and they both offer adding an indentation in their "transform object to string" method

JavaScript: JSON.stringify

space A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes.

If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than 10 is treated as if it were 10). Values less than 1 indicate that no space should be used.

If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array.

If space is anything other than a string or number (can be either a primitive or a wrapper object) — for example, is null or not provided — no white space is used.

Python: json.dumps

indent If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as "\t"), that string is used to indent each level.

Implementation: https://github.com/python/cpython/blob/ffb41eaaf4b04f7f52ee095253fcc1c5ba62ca28/Lib/json/encoder.py#L288-L295

I don' t really understand the length of 10 restriction in JS, so maybe just copy the python behavior as it seems to cover pretty much anything?

LFSaw commented 1 year ago

there's btw. also the (rather minimal) JSON implementation of the FluCoMa peeps: https://github.com/flucoma/flucoma-sc/blob/main/release-packaging/Classes/FluidManipulationJSON.sc (but it doesn't really help in the prettyprint issue :) )

telephon commented 1 year ago

so maybe just copy the python behavior as it seems to cover pretty much anything?

yes, looks reasonable.