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

indent interface is different from python stdlib #317

Open
AnjoMan opened this issue Oct 15, 2018 · 2 comments
Open

indent interface is different from python stdlib #317

AnjoMan opened this issue Oct 15, 2018 · 2 comments

Comments

@AnjoMan
Copy link

AnjoMan commented Oct 15, 2018

Using python's native json encoder, I can do

# json with no indentation
>>> json.dumps({"foo": 1, "baz": 2}, indent=0)
'{\n"foo": 1,\n"baz": 2}'

# output is all on one line
>>> json.dumps({"foo": 1, "baz": 2}, indent=None)
'{"foo": 1, "baz": 2}'

However, with ujson i get different behaviour with both of these

# ujson gives me output all on one line when i specify 0 indentation
>>> ujson.dumps({"foo": 1, "baz": 2}, indent=0)
'{"foo": 1, "baz": 2}'

# ujson fails if I pass in None
>>> ujson.dumps({"foo": 1, "baz": 2}, indent=None)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-e18a04872c22> in <module>()
----> 1 ujson.dumps({"foo": 1, "baz": 2}, indent=None)

TypeError: an integer is required (got type NoneType)
@AnjoMan
Copy link
Author

AnjoMan commented Oct 15, 2018

Is there interest in fixing this? I would be willing to poke around and try to find a solution, but not if it isn't a welcome change. I could use a hint about where to start though, as I've never worked with python bindings to c before.

@hugovk
Copy link
Member

hugovk commented Mar 13, 2020

@AnjoMan Hello! If you're still interested, looks like this is the relevant chunk:

static void Buffer_AppendIndentNewlineUnchecked(JSONObjectEncoder *enc)
{
if (enc->indent > 0) Buffer_AppendCharUnchecked(enc, '\n');
}
static void Buffer_AppendIndentUnchecked(JSONObjectEncoder *enc, JSINT32 value)
{
int i;
if (enc->indent > 0)
while (value-- > 0)
for (i = 0; i < enc->indent; i++)
Buffer_AppendCharUnchecked(enc, ' ');
}

And it should do this, to handle non-integers:

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.

https://docs.python.org/3/library/json.html#basic-usage

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

No branches or pull requests

2 participants