-
Hi There! Excellent library. Wondering if there is a simple way to unmarshal ROS messages in JSON format without modifying the autogenerated goroslib messages. The timestamp in the header needs to be converted. {
"header": {
"seq": 30,
"stamp": {
"secs": 1645759057,
"nsecs": 548703427
},
"frame_id": "world"
},
} type Header struct {
msg.Package `ros:"std_msgs"`
Seq uint32
Stamp time.Time
FrameId string
} |
Beta Was this translation helpful? Give feedback.
Answered by
aler9
Apr 18, 2022
Replies: 1 comment 1 reply
-
You can convert any ROS message to the JSON format in this way: type Header struct {
msg.Package `ros:"std_msgs"`
Seq uint32
Stamp time.Time
FrameId string
}
b, err := json.Marshal(&Header{
Seq: 33,
Stamp: time.Now(),
FrameId: "asd",
})
if err != nil {
panic(err)
} resulting in
The problem of your JSON format is that:
Therefore, if you still want to use it, you have take into consideration these changes: package main
import (
"encoding/json"
"fmt"
"time"
"unicode"
"github.com/aler9/goroslib/pkg/msgs/std_msgs"
)
func snakeToCamel(in string) string {
tmp := []rune(in)
tmp[0] = unicode.ToUpper(tmp[0])
for i := 0; i < len(tmp); i++ {
if tmp[i] == '_' {
tmp[i+1] = unicode.ToUpper(tmp[i+1])
tmp = append(tmp[:i], tmp[i+1:]...)
i--
}
}
return string(tmp)
}
func main() {
var b = []byte(`{` +
`"seq": 30,` +
`"stamp": {` +
` "secs": 1645759057,` +
` "nsecs": 548703427` +
`},` +
`"frame_id": "world"` +
`}`)
var m map[string]interface{}
err := json.Unmarshal(b, &m)
if err != nil {
panic(err)
}
newm := map[string]interface{}{}
for key, val := range m {
// convert time from secs / nsec to RFC3339
if key == "stamp" {
secs := val.(map[string]interface{})["secs"].(float64)
nsecs := val.(map[string]interface{})["nsecs"].(float64)
val = time.UnixMicro(int64(secs*1000000 + nsecs/1000))
}
// convert keys from snake case to camel case
newm[snakeToCamel(key)] = val
}
b, err = json.Marshal(newm)
if err != nil {
panic(err)
}
var h std_msgs.Header
err = json.Unmarshal(b, &h)
if err != nil {
panic(err)
}
fmt.Println(h)
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
swarmt
# for free
to join this conversation on GitHub.
Already have an account?
# to comment
You can convert any ROS message to the JSON format in this way:
resulting in
The problem of your JSON format is that:
Therefore, if you still want to use it, you have take into consideration these changes: