【发布时间】:2019-01-11 11:33:33
【问题描述】:
我想看看当我使用 json.loads() 将 json 字符串转换为 python 字典时正在执行什么代码
例如
import json
s = '{"a": 1, "b": 2}' # input json string
d = json.loads(s) # output dictionary object
我试图通过调试代码并达到核心逻辑和解析来了解内部逻辑。
import json
s = '{"a": 1, "b": 2}' # input json string
import pdb; pdb.set_trace()
d = json.loads(s) # output dictionary object
通过进入d = json.loads(s),我可以访问json/init.py 中的loads()
这进一步带我进入decode(),然后进入json/decoder.pyJSONDecoder 类中的raw_decode() 方法@
def raw_decode(self, s, idx=0):
"""Decode a JSON document from ``s`` (a ``str`` beginning with
a JSON document) and return a 2-tuple of the Python
representation and the index in ``s`` where the document ended.
This can be used to decode a JSON document from a string that may
have extraneous data at the end.
"""
try:
obj, end = self.scan_once(s, idx)
except StopIteration as err:
raise JSONDecodeError("Expecting value", s, err.value) from None
return obj, end
在raw_decode() 我无法进一步进入obj, end = self.scan_once(s, idx) pdd 将我发送到最后一行return obj, end
(Pdb) l
350 This can be used to decode a JSON document from a string that may
351 have extraneous data at the end.
352
353 """
354 try:
355 -> obj, end = self.scan_once(s, idx)
356 except StopIteration as err:
357 raise JSONDecodeError("Expecting value", s, err.value) from None
358 return obj, end
[EOF]
(Pdb) s
> /usr/lib/python3.6/json/decoder.py(358)raw_decode()
-> return obj, end
(Pdb)
我想查看内部代码,并且我希望使用 pdb 访问该代码,因为我期望通过进入 pdb 将进入内部代码。
我什至无法在json/scanner.py 和_json 模块中访问make_scanner = c_make_scanner or py_make_scanner。
如何使用调试实现核心迭代和解析逻辑?
【问题讨论】:
-
d 在 pdb 中保留。为变量使用不同的名称。超过两个字符的内容。