Victor Medrano
Victor Medrano

Reputation: 11

How to unmarshal this json string

I'm having some problem reading this type of json.

["Msg",{"cmd":"ack","id":"B81DA375B6C4AA49D262","ack":2,"from":"[email protected]","to":"[email protected]","t":1555446115}]

i try with many libraries.

type SEND struct {
    Mgs string `json:"Msg"`
    //SEND MSG
}

type MSG struct {
    CMD  string `json:"cmd"`
    ID   string `json:"id"`
    ACK  int    `json:"ack"`
    FROM string `json:"from"`
    TO   string `json:"to"`
    T    int64  `json:"t"`
}

func main() {
    data := `["Msg",{"cmd":"ack","id":"B81DA375B6C4AA49D262","ack":2,"from":"[email protected]","to":"[email protected]","t":1555446115}] `
    var dd SEND
    err := json.Valid([]byte(data))
    fmt.Println("Is valid XML?->", err)
    json.Unmarshal([]byte(data), &dd)
    fmt.Println("1", dd)
    fmt.Println("2", dd.Mgs)

}

Al always a receive empty and the json it's valid

Is valid XML?-> true
1 {}
2 EMPTY

Upvotes: 1

Views: 125

Answers (1)

cn0047
cn0047

Reputation: 17051

In this case you have array with string and object in your json, so you have to use interface{} on golang side, must be something like:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    data := `["Msg",{"cmd":"ack","id":"B81DA375B6C4AA49D262","ack":2,"from":"[email protected]","to":"[email protected]","t":1555446115}] `
    var d []interface{}
    err := json.Unmarshal([]byte(data), &d)
    fmt.Printf("err: %v \n", err)
    fmt.Printf("d: %#v \n", d[0])
    fmt.Printf("d: %#v \n", d[1])
}

Result will look like:

err: <nil>
d: "Msg"
d: map[string]interface {}{"id":"B81DA375B6C4AA49D262", "ack":2, "from":"[email protected]", "to":"[email protected]", "t":1.555446115e+09, "cmd":"ack"}

So 1st element in slice d is string Msg,
and 2nd element in slice is map map[string]interface {} and now you can do something else with this map.

Upvotes: 3

Related Questions