【问题标题】:Go: Reading JSON file vs. Reading JSON stringGo:读取 JSON 文件与读取 JSON 字符串
【发布时间】:2021-02-25 19:44:16
【问题描述】:

我有一个名为 example.json 的 JSON 文件,它看起来像:

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

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

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 32 32 32 34 44 44 44 4 44 112 32 32 3212 32 32 32 32 32 32 32 32 32 32 111 111 111 111 111 11411 111 11411 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时。

【问题讨论】:

  • 它们显然不同。 json.Marshal 将内容作为 JSON 编码字符串返回,而不是原始字符串
  • @Inian bytesVar := []byte(example) 的行为方式相同。如何将变量作为原始字符串读入字节?
  • 在json.Marshal 之后,你会得到一个 json 编码的字符串。没有编组,“它们看起来不同”是什么意思?什么是 bytesJSON 和什么是 bytesVar?
  • @BurakSerdar 更新了问题以描述他们的样子。
  • 您的bytesVar 与example 中的内容不匹配。它说"pubsub_example_topic"。 bytesJSON 里面有很多额外的东西。你的例子是对的吗?

标签: json parsing go


【解决方案1】:

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

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

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",
    }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-22
  • 2011-07-17
相关资源
最近更新 更多