Generic message to JSON converter in C++?
Hi, I'm trying to convert a message into a json string.
While it only takes 2 lines in python, this seems more complex in C++.
I have a working example for 1 message type (geometry/msgs/Twist)
void Foo::cmdVelCb(geometry_msgs::msg::Twist::SharedPtr msg)
{
std::string yaml_str = rosidl_generator_traits::to_yaml(*msg);
YAML::Node yaml_node = YAML::Load(yaml_str);
dc_interfaces::msg::StringStamped pub_msg;
nlohmann::json data_json;
data_json["linear"]["x"] = yaml_node["linear"]["x"].as<float>();
data_json["linear"]["y"] = yaml_node["linear"]["y"].as<float>();
data_json["linear"]["z"] = yaml_node["linear"]["z"].as<float>();
data_json["angular"]["x"] = yaml_node["angular"]["x"].as<float>();
data_json["angular"]["y"] = yaml_node["angular"]["y"].as<float>();
data_json["angular"]["z"] = yaml_node["angular"]["z"].as<float>();
}
But now I would like to have a generic way to do it since I will have many more types to handle. Any suggestion?
Thanks
Answer: I could not achieve a generic one but did this using https://github.com/mircodezorzi/tojson
std::string yaml_str = geometry_msgs::msg::to_yaml(*msg);
YAML::Node yaml_node = YAML::Load(yaml_str);
json data_json = tojson::detail::yaml2json(yaml_node);
This still requires to pass geometrymsgs::msg::toyaml which I would have liked to avoid.
Asked by Dben on 2022-11-08 06:18:42 UTC
Answers
In rclpy
you have a lot of functionality already built-in, e.g. based on this note:
Most ROS 2 users probably do not need this package. This package was originally developed for ROS 1. In ROS 2, most of the functionality is already built in. Specifically, check out
rosidl_runtime_py.set_message.set_message_fields()
for converting a Python dictionary to a ROS message, and
rosidl_runtime_py.convert.message_to_orderreddict
for converting a ROS message to a Python dictionary.
I tried to find similar functionality featured in rclpp
(without much success), but I found these packages mentioned:
- https://github.com/osrf/dynamic_message_introspection > This repo demonstrates how to do introspection of C and C++ messages. The dynmsg package can convert ROS 2 messages into a YAML representation, and convert a YAML representation into ROS 2 messages.
You can easily convert YAML to JSON in C++, e.g. https://github.com/mircodezorzi/tojson
Other links I read:
Asked by ljaniec on 2022-11-08 07:11:06 UTC
Comments
Thanks! I could use https://github.com/mircodezorzi/tojson . I added my solution as an edit using this library. I hesitated to accept the answer because I could get what I wanted but it does not fully answer the question (I could not achieve a generic function) since i still need to pass the message type to parse
Asked by Dben on 2022-11-19 15:37:15 UTC
Take a look at rosbag2
, it subscribes to serialized topics regardless of message type:
and this one from rclcpp
Asked by ljaniec on 2022-11-19 21:14:29 UTC
Comments