英文:
Unmarshaling failed, and it reports "invalid character '\x00' in string literal"
问题
你正在使用的 Go 版本是什么(go version
)?
$ go version go1.19.1
这个问题是否在最新版本中重现?
是的
你使用的操作系统和处理器架构是什么(go env
)?
Linux
你做了什么?
package main
import (
"encoding/json"
"fmt"
"strconv"
"strings"
)
func UnescapeUnicode(uContent string) (string, error) {
content := strings.Replace(strconv.Quote(uContent), `\\u`, `\u`, -1)
text, err := strconv.Unquote(content)
if err != nil {
return "", err
}
return text, nil
}
func main() {
v := "{\"aa\":\"some\\u0000\"}"
v2, _ := UnescapeUnicode(v)
var m = make(map[string]interface{})
err := json.Unmarshal([]byte(v2), &m)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(m)
}
你期望看到什么?
map[aa:some]
你看到了什么?
字符串文字中的无效字符'\x00'
英文:
What version of Go are you using (go version
)?
<pre>
$ go version
go1.19.1
</pre>
Does this issue reproduce with the latest release?
YES
What operating system and processor architecture are you using (go env
)?
Linux
What did you do?
package main
import (
"encoding/json"
"fmt"
"strconv"
"strings"
)
func UnescapeUnicode(uContent string) (string, error) {
content := strings.Replace(strconv.Quote(uContent), `\\u`, `\u`, -1)
text, err := strconv.Unquote(content)
if err != nil {
return "", err
}
return text, nil
}
func main() {
v := "{\"aa\":\"some\\u0000\"}"
v2, _ := UnescapeUnicode(v)
var m = make(map[string]interface{})
err := json.Unmarshal([]byte(v2), &m)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(m)
}
What did you expect to see?
map[aa:some]
What did you see instead?
invalid character '\x00' in string literal
答案1
得分: 0
你可以通过删除UnescapeUnicode
函数来修改主方法,如下所示。
func main() {
v := "{\"aa\":\"some\\u0000\"}"
var m = make(map[string]interface{})
err := json.Unmarshal([]byte(v), &m)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(m)
}
注意:
-
\u0000
是一个Unicode字符。为了在字符串中包含\u0000
,应将\u0000
替换为\\u0000
。 -
双引号(
"
)是保留字符,不能在JSON中使用,必须进行适当的转义才能在字符串中使用。因此,双引号应替换为\"
。 -
你不需要手动处理特殊字符转义。
json.Unmarshal
会处理它们。
英文:
You can change the main method as below by removing UnescapeUnicode
function.
func main() {
v := "{\"aa\":\"some\\u0000\"}"
var m = make(map[string]interface{})
err := json.Unmarshal([]byte(v), &m)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(m)
}
Note:
-
\u0000
is an unicode. In order to be included\u0000
in the string,\u0000
should be replaced with\\u0000
. -
Double quote (
"
) is a reserved characters and can not be used in JSON and must be properly escaped to be used in strings. For that, double quote should be replaced with\"
. -
You don't need to mannully handle Special Characters Escaping. It will be handled by
json.Unmarshal
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论