json.unmarshall在源数据中存在换行符时会失败。

huangapple go评论84阅读模式
英文:

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}

huangapple
  • 本文由 发表于 2022年8月28日 15:39:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/73516846.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定