我有一個名為的 JSON 文件example.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) }兩者都是 type []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 58 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.
1 回答

開滿天機
TA貢獻1786條經驗 獲得超13個贊
注意:問題中的“編輯”輸出使用的示例輸入與問題中的不同。
如果我們將它們打印為字符串,它就會變得清晰。
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",
}
- 1 回答
- 0 關注
- 189 瀏覽
添加回答
舉報
0/150
提交
取消