登录
首页 >  Golang >  Go问答

当源数据中有新行时 json.unmarshall 失败

来源:stackoverflow

时间:2024-02-12 14:27:23 390浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《当源数据中有新行时 json.unmarshall 失败》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

我正在通过 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)
}

我期待 res 响应结构中的输出,但是我得到的是空响应。

当前输出:

json string is 

    {"data1": "this is 
        test data 1", 
        "data2": "this is test data 2"}

structure output is 

{ }

有没有办法通过 json.unmarshal 获得正确的结构输出?


正确答案


来自 json.unmarshal 的被忽略的错误是

error invalid character '\n' in string literal

如果您想在 data1 中换行,请将 str 更改为

str := `{"data1": "this is \n test data 1", 
    "data2": "this is test data 2"}`

然后输出将是

structure output is 
{this is 
 test data 1 this is test data 2}

今天关于《当源数据中有新行时 json.unmarshall 失败》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>