Skip to main content
 首页 » 编程设计

Python JSON 模块不会为无效的 JSON 抛出异常

2025年05月04日10pengyingh

那么,有效的 JSON 必须是对象或数组,对吗?我原以为以下代码会引发异常,但事实并非如此:

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

请您参考如下方法:

这不是无效的 JSON*。 Number 是一个有效的 JSON 类型,就像对象一样。 http://en.wikipedia.org/wiki/JSON#Data_types.2C_syntax_and_example这些类型中的任何一种都可以单独出现,尽管对象和数组可能是最常见的顶级类型。

*根据python实现

编辑:

正如在删除的(不确定为什么)答案中指出的那样,python 文档建议 JSON RFC 确实要求顶级对象是数组或对象类型,但是 json 模块不强制执行此操作。由于我对 JSON 的很多了解都来自于使用 python json 模块,所以我不知道这种行为的可移植性如何。

根据要求,这在 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.