4

See the following code:

>>> import json
>>> m = {}
>>> m[0.0] = 1.0
>>> json.dumps(m)
'{"0.0": 1.0}'

In the value of the JSON, we have 1.0. But in the key we have "0.0" (a Json string).

This ambiguous handling of floats just cost me some debugging time. Does anyone know why python's json module does this?

1 Answer 1

9

Because a JSON key must be a string. See the RFC.

Sign up to request clarification or add additional context in comments.

2 Comments

It's worth noting that despite popular opinion, JSON is precisely defined subset of Javascript, not just anything that's valid javascript literals. Although this case, IMO, should probably have thrown an exception.
Agreed, should have thrown an exception in this case, it would've been clearer to me from the outset. Python's cjson module does this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.