如何定位JSON文件中指定路径对应数据的行列位置?
问题:JSON配置解析器如何根据路径定位源文件的行号和列号?
我正在编写一个以JSON文件作为配置的解析器,当检测到无效值时,希望能以源文件中的行号和列号形式输出问题数据的位置。目前已经完成路径追踪,能得到问题数据的路径列表(每个元素是对象键或数组索引,比如["foo", "bar", 3, "baz"]),但没法通过这个路径确定它在文件中的具体位置。
理想情况下,错误处理代码应输出如下内容:
ValidationError: Features require a "feature" at .features[0]: "theme.json" line 6, column 13
我尝试过使用自定义JSONDecoder,通过JSONDecoder.object_hook挂钩对象处理,但该函数提供的信息不足,且没有针对数组的挂钩方法。
以下是我定义的错误类代码:
import typing class JSONTraceable(Exception): def __init__( self, message: str, json_path: typing.Union[str, typing.List[typing.Union[str, int]]] = "", ): super().__init__(message) if isinstance(json_path, str): self.json_path = [json_path] elif isinstance(json_path, list): self.json_path = json_path else: raise TypeError( f"JSON path should be a string or a list, not {type(json_path).__name__}" ) def extend(self, key: typing.Union[str, int]): self.json_path.insert(0, key)
内容的提问来源于stack exchange,提问作者PenguinEncounter
相关产品推荐
相关产品推荐

