简体   繁体   中英

Python JSON module not throwing exception for invalid JSON

So, valid JSON must be an Object or Array, correct? I was expecting the following code to throw an exception but it is not:

>>> import json
>>> json.loads("245235")
245235

That's not invalid JSON*. Number is a valid JSON type, just like object. http://en.wikipedia.org/wiki/JSON#Data_types.2C_syntax_and_example any of these types could appear on its own, albeit that object and array are probably the most common top level types.

*according to the python implementation

EDIT:

As pointed out in a deleted (not sure why) answer, the python docs suggest that the JSON RFC does require the top level object to be of array or object type, but that the json module doesn't enforce this. Since a lot of what I know about JSON has come from working with the python json module, I don't know how portable this behavior is.

As requested, this is noted at http://docs.python.org/2/library/json.html#standard-compliance :

This module does not comply with the RFC in a strict fashion, implementing some extensions that are valid JavaScript but not valid JSON. In particular:

  • Top-level non-object, non-array values are accepted and output;
  • Infinite and NaN number values are accepted and output;
  • Repeated names within an object are accepted, and only the value of the last name-value pair is used.

JSON数据可以具有多种类型,包括字符串,数字和布尔值

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM