-4

I have a JSON file called example.json that looks like:

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

I also have a variable representing the above as a "string":

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

I am trying to understand why reading the contents of the JSON file into bytes is different from reading the contents of the example variable. My code is as follows:

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

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

Both are of the type []uint8, but look very different. Any ideas on why? And how I can make sure that they are always the same?

EDIT: Even using bytesVar := []byte(example) results in the same issue.

EDIT:

bytesJSON looks like:

[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 looks like:

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

when printed to stdout.

readytotaste
  • 199
  • 2
  • 4
  • 17

1 Answers1

2

Note: The "edit" output in the question is using different example input than in the question.

If we print them as strings it becomes clear.

fmt.Println(string(bytesJSON))

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

ioutil.ReadFile is just what's in the file.

fmt.Println(string(bytesVar))

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

json.Marshal has encoded the string example as JSON. That is a JSON string containing a string.

The equivalent to ioutil.ReadFile("example.json") is simply example.

If we unmarshal bytesVar we get back the original string in example.

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

{
        "name": "example",
        "type": "record",
    }
Schwern
  • 153,029
  • 25
  • 195
  • 336
  • Thanks, this helps. But, `ioutil.ReadFile("example.json")` returns bytes - while `example` is of string type. Is there a way for me to get the equivalent of `example` in bytes? – readytotaste Nov 13 '20 at 20:01
  • 3
    @walksignison [How to assign string to bytes array](https://stackoverflow.com/questions/8032170/how-to-assign-string-to-bytes-array). I'd recommend giving [Effective Go](https://golang.org/doc/effective_go.html) and [Go By Example](https://gobyexample.com/) a... go. – Schwern Nov 13 '20 at 20:04