Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add msgspec.json.format function #226

Merged
merged 1 commit into from Dec 6, 2022
Merged

Add msgspec.json.format function #226

merged 1 commit into from Dec 6, 2022

Conversation

jcrist
Copy link
Owner

@jcrist jcrist commented Dec 6, 2022

This takes an existing JSON document and reformats it, adding/removing whitespace as needed. The formatting is done efficiently, for common use cases the overhead should be negligible.

Demo:

In [1]: import msgspec                         

In [2]: msg = b'{"a":[1,2,{"x":2}]}'  # an existing JSON message

In [3]: print(msgspec.json.format(msg).decode())  # pretty print
{                                              
  "a": [                                       
    1,                                         
    2,                                         
    {                                          
      "x": 2                                   
    }                                          
  ]                                            
}                                              

In [4]: print(msgspec.json.format(msg, indent=4).decode())  # configurable indent size
{                                              
    "a": [                                     
        1,                                     
        2,                                     
        {                                      
            "x": 2                             
        }                                      
    ]                                          
}                                              

In [5]: print(msgspec.json.format(msg, indent=0).decode())  # indent 0 only adds spaces
{"a": [1, 2, {"x": 2}]}

In [6]: formatted = msgspec.json.format(msg)

In [7]: print(msgspec.json.format(formatted, indent=-1).decode())  # indent < 0 minimizes
{"a":[1,2,{"x":2}]}

Fixes #219.

This takes an existing JSON document and pretty-prints it for human
consumption. Currently this only supports indenting array/object items,
but sorting keys (or other options) *may* be in scope.
@jcrist jcrist merged commit 83d2f1b into main Dec 6, 2022
@jcrist jcrist deleted the json-format branch December 6, 2022 16:44
@jcrist jcrist mentioned this pull request Dec 6, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Indentation formatting
1 participant