'Does it make sense to `json.loads` to accept booleans, null and numbers as a JSON string?
I ran into this issue while challenging the Python json.loads method.
As I understand it this method should convert a stringified JSON structure in a:
- Python
dictwhile parsing a JSON structured as a map - Python
listwhile parsing a JSON structured as an array
So far these behaviours are okay:
import json
>>> json.loads("{\"hello\": \"world\"}")
{'hello': 'world'}
>>> json.loads("[{\"hello\": \"world\"}]")
[{'hello': 'world'}]
And it is also okay to raise an exception when string has nothing to deal with a JSON structure:
>>> json.loads("abc")
...
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
But then how is it consistent to convert strings that represent booleans, null and numbers?:
>>> json.loads("true")
True
>>> json.loads("false")
False
>>> json.loads("null") is None
True
>>> json.loads("1")
1
>>> json.loads("1.0")
1.0
Solution 1:[1]
The first parameter of json.loads is a Python string, which is usually filled with a value with double quotes to denote it is a Python string literal.
In your example of raising an exception, if you mean "abc" as a JSON string, you should write the code as:
json.loads('"abc"')
the inner double quotes is part of content of JSON text, which fits the requirement of JSON string of standard RFC 7159.
how is it consistent to convert strings that represent booleans, null and numbers?
Also refer to standard:
A JSON value MUST be an object, array, number, or string, or one of the following three literal names:
false null trueThe literal names MUST be lowercase. No other literal names are
allowed.
So these are allowed while abc raises an exception.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rustyhu |
