登录
首页 >  Golang >  Go问答

解析 JSON:文件和字符串的读取

来源:stackoverflow

时间:2024-03-29 15:00:30 279浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《解析 JSON:文件和字符串的读取》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

我有一个名为 example.json 的 json 文件,如下所示:

35538​​4782843

我还有一个变量将上述内容表示为“字符串”:

const example = `{
    "name": "example",
    "type": "record",
}`

我试图理解为什么将 json 文件的内容读取为字节与读取 example 变量的内容不同。我的代码如下:

bytesJSON, err := ioutil.ReadFile("example.json")
    if err != nil {
        fmt.Println(err)
    }

    bytesVar, err := json.Marshal(example)
    if err != nil {
        fmt.Println(err)
    }

两者都是 []uint8 类型,但看起来非常不同。有什么想法吗?我如何确保它们始终相同?

编辑:即使使用 bytesvar := []byte(example) 也会导致同样的问题。

编辑:

bytesjson 看起来像:

[123 10 32 32 32 32 34 110 97 109 101 34 58 32 34 101 120 97 109 112 108 101 34 44 10 32 32 32 32 34 116 121 112 101 34 5 8 32 34 114 101 99 111 114 100 34 10 125]

bytesvar 看起来像:

[34 112 117 98 115 117 98 95 101 120 97 109 112 108 101 95 116 111 112 105 99 34]

打印到 stdout 时。


解决方案


注意:问题中的“编辑”输出使用与问题中不同的示例输入。

如果我们将它们打印为字符串,它就会变得清晰。

fmt.println(string(bytesjson))

{
    "name": "example",
    "type": "record",
}

ioutil.readfile 就是文件中的内容。

fmt.println(string(bytesvar))

"{\n        \"name\": \"example\",\n        \"type\": \"record\",\n    }"

json.Marshal 已将字符串 example 编码为 json。那是一个包含字符串的 json 字符串。

ioutil.readfile("example.json") 等效的只是 example

如果我们解组 bytesvar,我们会在 example 中返回原始字符串。

var unmarshal string;
json.Unmarshal(bytesVar,&unmarshal)
fmt.Println(unmarshal)

{
        "name": "example",
        "type": "record",
    }

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

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