Supporting non-string Numpy keys #623
Open
+388
−74
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hello!
I'm a fan of orjson and use it extensively. Thanks for the great work!
I recently found myself trying to serialize a dict containing numpy floats for keys and found that while orjson supports serializing numpy, and it supports serializing non-string keys, it does not supporting serializing non-string numpy keys. This PR hopefully introduces support for this in a nice way. I'm not the first person to have encountered this issue, for example #604 .
From the contribution guidelines, I think my checklist to completion looks something like:
test_non_str_keys.pyto cover all the same Numpy scalar types covered intest_numpy.py.serde_json::to_string(...)to reuse the existing serializer implementation forNumpyScalarbut this (A) doesn't feel very efficient, and (B) ruined datetimes. Instead I made ato_string()implementation which is very similar.numpy.datetime64and this returns a serialization error if it's invalid.Benchmarks
Here are some micro-benchmarks:
From this we can draw some conclusions:
orjson.dumpsserializations are faster thanjson.dumps.numpy.int64it is ~40% faster to use the extra option.np.datetime64values, it is surprisingly faster (by a wide margin) to convert each date into a string in Python and then to useorjson.dumps(...)without options. Lines 4-6 we see for 36.5k dates it takes almost 1/3rd the time to stringify outside of orjson. I was a bit surprised by this and found for much larger datasets the relative improvement is less, but it's still there.np.datetime64and 36.5kstrs: once with numpy as the values (using the existing option) and once with numpy as the keys (using the new option). Here the serialization time with numpy keys is still slightly slower, but well within the error of the two samples.