英文:
json.unmarshall fails when there are new lines in source data
问题
我正在通过Go运行以下代码片段:
package main
import (
"encoding/json"
"fmt"
)
type response struct {
Data1 string `json:"data1"`
Data2 string `json:"data2"`
}
func main() {
//源数据
str := `{"data1": "this is test data 1", "data2": "this is test data 2"}`
res := response{}
fmt.Println("json字符串为:")
fmt.Println(str)
json.Unmarshal([]byte(str), &res)
fmt.Println("结构输出为:")
fmt.Println(res)
}
我期望在res
的响应结构中获得输出,但是我得到的是空的响应。
当前输出:
json字符串为:
{"data1": "this is test data 1", "data2": "this is test data 2"}
结构输出为:
{}
有没有办法通过json.Unmarshal
获得正确的结构输出?
英文:
I am running the below code snippet via Go:
package main
import (
"encoding/json"
"fmt"
)
type response struct {
Data1 string `json:"data1"`
Data2 string `json:"data2"`
}
func main() {
//source data
str := `{"data1": "this is
test data 1",
"data2": "this is test data 2"}`
res := response{}
fmt.Println("json string is \n")
fmt.Println(str)
json.Unmarshal([]byte(str), &res)
fmt.Println("structure output is \n")
fmt.Println(res)
}
I am expecting output in res response struct, however I am getting empty responses.
Current Output:
json string is
{"data1": "this is
test data 1",
"data2": "this is test data 2"}
structure output is
{ }
Is there a way we can get proper structure output via json.Unmarshal?
答案1
得分: 2
json.Unmarshal
的忽略错误是:
错误:字符串文字中的无效字符'\n'
如果你想在 data1
中换行,将 str
改为:
str := `{"data1": "this is \n test data 1",
"data2": "this is test data 2"}`
然后输出将会是:
结构输出是
{this is
test data 1 this is test data 2}
英文:
The ignored error from json.Unmarshal
is
Error invalid character '\n' in string literal
If you want a newline in data1 change str
to
str := `{"data1": "this is \n test data 1",
"data2": "this is test data 2"}`
Then output will be
structure output is
{this is
test data 1 this is test data 2}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论