Skip to content

Add msgspec.json.format function - #226

Merged
jcrist merged 1 commit into
mainfrom
json-format
Dec 6, 2022
Merged

jcrist merged 1 commit into
mainfrom
json-format

Conversation

@jcrist

@jcrist jcrist commented Dec 6, 2022

Copy link
Copy Markdown
Member

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