4

I'm writting a piece of Go to send json data on multicast udp:

func send(a string, messages chan interface{}) {
    addr, err := net.ResolveUDPAddr("udp", a)
    CheckError(err)
    c, err := net.DialUDP("udp", nil, addr)
    CheckError(err)
    for {
        msg := <-messages
        myjson, err := json.Marshal(msg)
        if err != nil {
            fmt.Println("Error encoding JSON")
        return
        }
        //Write to bytes to multicast UDP
        c.Write([]byte(myjson))

        time.Sleep(2 * time.Second)
    }
}

So my json is converted to an array of byte to make it work. Here is my "receiver" func:

func serveMulticastUDP(a string, messages chan interface{}) {

    addr, err := net.ResolveUDPAddr("udp", a)
    CheckError(err)
    l, err := net.ListenMulticastUDP("udp", nil, addr)
    l.SetReadBuffer(maxDatagramSize)
    for {
        b := make([]byte, maxDatagramSize)
        n, src, err := l.ReadFromUDP(b)
        if err != nil {
            log.Fatal("ReadFromUDP failed:", err)
        }
        s := string(b[:n])//here is my problem, I want s to be map[string]interface before sending in my channel
        messages<-s
        log.Println(s)
        log.Println(src)
        log.Println(n)
        //h(src, n, b)
    }
}

How can convert a array of bytes to map[string]interface (json) ?

r3dlight
  • 101
  • 8

1 Answers1

5

In your code you used json.Marshal() to convert your value to JSON text ([]byte).

The other direction ([]byte -> value) can be done using json.Unmarshal(). json.Unmarshal() expects a []byte so you don't even have to convert it to string.

See this example:

data := []byte(`{"key1":"value1","key2":123}`)

var m map[string]interface{}
if err := json.Unmarshal(data, &m); err != nil {
    panic(err)
}

fmt.Printf("%+v", m)

Output (try it on the Go Playground):

map[key1:value1 key2:123]

Notes:

The result of marshaling (json.Marshal()) is a value of type []byte so you don't need explicit conversion here:

c.Write([]byte(myjson))

You can simply write:

c.Write(myjson)

Also when unmarshaling, make sure you pass b[:n] to json.Unmarshal(), as the rest of the slice contains 0s (which your 2nd error suggests) but they are not part of the json text!

icza
  • 389,944
  • 63
  • 907
  • 827
  • Thank you icza, now I have another issue, it does panic when unmarshalling my byte array : unexpected end of json input. Should I open a new question with more details ? – r3dlight Dec 02 '15 at 10:31
  • 1
    That means the `[]byte` you're passing to `json.Unmarshal()` is not the complete JSON encoded text. It could be even empty. Make sure it contains the whole json text (check its content). – icza Dec 02 '15 at 10:33
  • I understand (my json is quite huge vs UDP), could you suggest me a way to check the content properly ? – r3dlight Dec 02 '15 at 10:37
  • 1
    @r3dlight Just print it e.g. `fmt.Println(n, string(b[:n]), b[:n])`. – icza Dec 02 '15 at 11:08
  • Ok, first I increased my maxDatagramSize to 18000. Then I made the print like you suggested : 16115 {...}[...] It seems to be complete but now I panic with panic: invalid character '\x00' after top-level value – r3dlight Dec 02 '15 at 11:20
  • 3
    @r3dlight Make sure you pass `b[:n]` to `json.Unmarshal()`, as the rest of the slice contains `0`s (which your error suggests) but they are not part of the json text! – icza Dec 02 '15 at 11:27