Skip to content

Instantly share code, notes, and snippets.

@agrueneberg
Created April 30, 2023 21:52
Show Gist options
  • Save agrueneberg/b657d5ad31cb65d89a80535627c12d0b to your computer and use it in GitHub Desktop.
Save agrueneberg/b657d5ad31cb65d89a80535627c12d0b to your computer and use it in GitHub Desktop.
ROS messages to JSON and back
import os
import importlib
import rosidl_runtime_py
import json
def get_msg_type(type):
symbol = os.path.basename(type)
module = ".".join(os.path.split(os.path.dirname(type)))
return getattr(importlib.import_module(module), symbol)
def __msg_to_dict(msg):
return rosidl_runtime_py.message_to_ordereddict(msg)
def __dict_to_msg(type_name, values):
instance = get_msg_type(type_name)()
rosidl_runtime_py.set_message_fields(instance, values)
return instance
def msg_to_json(msg):
return json.dumps(__msg_to_dict(msg))
def json_to_msg(type_name, json_string):
return __dict_to_msg(type_name, json.loads(json_string))
# Example
Pose = get_msg_type('turtlesim/msg/Pose')
p = Pose()
p.x = 1.0
p.y = 2.0
p.x = 4.653351783752441
p.y = 5.970754623413086
p.theta = -0.9212489724159241
p.linear_velocity = 2.0
p.angular_velocity = 1.7999999523162842
json_string = msg_to_json(p)
q = json_to_msg('turtlesim/msg/Pose', json_string)
p == q
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment