How do you locate the end of the first JSON value in a concatenated buffer?
raw_decode parses one JSON value from the start of a string and returns the index immediately after it.
Python example and interpretation
For [1] followed immediately by [2], decode the first and retain the tail. A network chunk ending mid-value needs more bytes before parsing can finish.
import json
s='[1][2]'
value,end=json.JSONDecoder().raw_decode(s)
[value,end,s[end:]]Result [[1], 3, '[2]']
中文
连续收到两个 JSON 值时,怎样找到第一个值的结束位置?
raw_decode 从字符串开头解析一个完整 JSON 值,同时返回其后的字符下标。
Python 算例与适用条件
缓冲区 [1] 后紧跟 [2],先解出第一段再保留余串。网络块若还未包含完整值,须等待更多数据再解析。
import json
s='[1][2]'
value,end=json.JSONDecoder().raw_decode(s)
[value,end,s[end:]]结果 [[1], 3, '[2]']