【问题标题】:"invalid character '\x00' after top-level value"“顶级值后的无效字符 '\x00'”
【发布时间】:2014-08-07 16:32:57
【问题描述】:

在 for 循环中解组 json 时出现此错误。 第一次通过循环解组很好,但在下一次迭代中我得到了这个错误。

我是 golang 新手,这个错误信息不清楚。有人可以解释在什么情况下会发生此错误以及我应该如何避免它。

【问题讨论】:

  • 请贴一些代码。
  • 标题中有两个反斜杠。错误消息是真的说'\\x00' 还是只是'\x00'
  • 不,只有一个,像这样:[顶级值后的无效字符'\x00']

标签: json go


【解决方案1】:

encoding/json/scanner.go的源码

// stateEndTop is the state after finishing the top-level value,
// such as after reading `{}` or `[1,2,3]`.
// Only space characters should be seen now.
func stateEndTop(s *scanner, c int) int {
    if c != ' ' && c != '\t' && c != '\r' && c != '\n' {
        // Complain about non-space byte on next call.
        s.error(c, "after top-level value")
    }
    return scanEnd
}

所以检查一下你的 JSON 字符串是如何结束的。

例如,在this thread 中,说明一个潜在问题:

ReadFromUDP 可以返回任何大小的数据包,从 1 到 2000 字节,您需要使用实际读取的字节数重新切片缓冲区。

json.Unmarshal(buf[:n], &msg)

this thread 中相同:

request := make([]byte, 1024)
read_len, err := conn.Read(request)
request_right := request[:read_len]
j := new(Json)
err := j.UnmarshalJSON(request) // not working

如果read_len < len(request) 那么请求最后会包含额外的“\x00” 这就是UnmarshalJSON(request) 不起作用的原因。

【讨论】:

    【解决方案2】:

    感谢您回答我的问题。

    这个错误是由于不正确的 json 造成的,之前没有更多的故事,

    我有一个 json.RawMessage 类型的字段 detail 我有 SELECT 查询,我试图从表中读取 json 并扫描到 detail 并将其附加到结构。

    当我查看 detail JSON 时,for 循环结束后,它会多次获得相同的记录,有无结束大括号。经过深思熟虑后,我发现使用 byte 进行投射细节很有帮助。

    例如:不只是 rows.Scan(&detail) 试试这个: rows.Scan((*[]byte)(&detail)) 解决了上面的问题

    【讨论】:

    • 很好的反馈,比我的回答更准确。 +1
    猜你喜欢
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 2022-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-10
    • 2012-01-14
    相关资源
    最近更新 更多