0

I'm trying to parse a json object, get a specific field session_id as []byte.

func login() {
    var jsonObj map[string]interface{}
    json.Unmarshal(body, &jsonObj)
    content := jsonObj["content"].(map[string]interface{})
    sid := content["session_id"].([]byte)
}

Where, body is the json object from the HTTP response. It looks like this:

{
    "seq": 0,
    "status": 0,
    "content": {
        "session_id": "abcd1234efgh5678",
        "config": {
            "icons_dir": "feed-icons",
            "icons_url": "feed-icons",
            "daemon_is_running": true,
            "custom_sort_types": [],
            "num_feeds": 2
        },
        "api_level": 18
    }
}

My code panics on the last line, saying: panic: interface conversion: interface {} is string, not []uint8

If I change the last line to below then it works:

    sid := content["session_id"].(string)
    sidbytes := []byte(sid)

I'm assuming in the error message "interface {} is string" refers to "abcd1234efgh5678" being a string, and uint8 is byte (which makes sense but)? What am I misunderstanding here?

anetworknoobie
  • 69
  • 1
  • 1
  • 7
  • Explicit casts in Go only match on the actual underlying type - in this case an object of type string. Your second conversion, from `string` to `[]byte`, is probably the normal way. – selbie Apr 30 '22 at 15:16
  • 2
    There are no casts in Go, a type assertion only asserts the type stored in the interface. If you want to convert the value to a slice, assert the correct type (string in this case) then convert. – JimB Apr 30 '22 at 16:11
  • 3
    Your own change is the correct answer to the problem. What you are misunderstanding is that a Type Assertion is NOT a Type Conversion. – Bazzz Apr 30 '22 at 16:47

1 Answers1

0

You can use session_id as []byte because it is not an array byte, If you pay attention to its name you see it is a slice of byte, but your JSON is a string. so you cant get it as a []byte.

What you should do

What you did is the correct way and correct answer to your problem.

If you generate Json by yourself, you can set session_id to a slice of byte, so in unmarshalling you can get it as []byte

ttrasn
  • 4,322
  • 4
  • 26
  • 43