Ask Your Question
0

How to publish a dictionary with other dictionary inside in a topic?

asked 2018-11-04 10:02:51 -0500

Ivan_Sanchez gravatar image

Hi all,

I'm trying to publish in a topic a dictionary with other dictionary inside so other ROS node is able to access to that information, but I do not know how can I do it. Anyone has any idea?

Thanks for your help!

edit retag flag offensive close merge delete

Comments

Which language are you using?

NEngelhard gravatar image NEngelhard  ( 2018-11-04 11:08:01 -0500 )edit

1 Answer

Sort by ยป oldest newest most voted
0

answered 2018-11-04 12:57:56 -0500

A dictionary is a concept supported by Python but not by C++ or ROS so you cannot add a dictionary directly to a message. However you can use a standard data definition language such as JSON and transport that data using a std_msgs/String message. This would have the advantage of being human readable if you need to debug the messages in transit too.

In python you could pack or unpack the JSON as below:

import json

encoded_data_string = json.dumps({... your dictionary ...})

loaded_dictionary = json.loads(encoded_data_string)

In a C++ node you could use the boost JSON module to read, store and write the data. The example below fills a boost::property tree object with JSON from a file, but could be adapted to read JSON from a std_msgs/String message.

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

// Short alias for this namespace
namespace pt = boost::property_tree;

// Create a root
pt::ptree root;

// Load the json file in this ptree
pt::read_json("filename.json", root);

Hope this helps.

edit flag offensive delete link more

Comments

While this solves the question that the OP asks, using string and serialise JSON into it is really not something I would recommend: the msg has no semantics and is opaque to nodes that don't "know" how to interprete the string.

ROS msgs and services are supposed to make up a ROS API, so something that can be used to interface with a (set of) node(s) without any knowledge of the implementation details.

Setting something up like that (ie: the ROS API) takes some effort, and plunking dictionaries into string fields is not something that should be done lightly.

gvdhoorn gravatar image gvdhoorn  ( 2018-11-05 02:12:31 -0500 )edit

Why not create your own ROS msg? In this way you could code the informations as you whish

Kappa95 gravatar image Kappa95  ( 2021-03-08 12:57:58 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2018-11-04 10:02:51 -0500

Seen: 2,608 times

Last updated: Nov 04 '18