1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

nlohmann-json c++ ros

Last updated at Posted at 2022-12-25

下記環境でnlohmann-json3ライブラリを使った際のメモ

ubuntu20.04
ros noetic
  • install
sudo apt install nlohmann-json3-dev
  • 1: 次のようなjsonオブジェクトを作成したい場合
{
  "pi": 3.141,
  "happy": true,
  "name": "Niels",
  "nothing": null,
  "answer": {
    "everything": 42
  },
  "list": [1, 0, 2],
  "object": {
    "currency": "USD",
    "value": 42.99
  }
}

~.cpp内追加内容

xxx.cpp
// header & namespace
#include <nlohmann/json.hpp> 
using json = nlohmann::json;

// create json object
int main(int argc, char** argv)
{

  json j;
  j["pi"] = 3.141;
  j["happy"] = true;
  j["name"] = "Niels";
  j["nothing"] = nullptr;
  j["answer"]["everything"] = 42;  // 存在しないキーを指定するとobjectが構築される
  j["list"] = { 1, 0, 2 };         // [1,0,2]
  j["object"] = { {"currency", "USD"}, {"value", 42.99} };  // {"currentcy": "USD", "value": 42.99}

  std::cout << j << std::endl;  // coutに渡せば出力できる。
}
  • 2: json文字列をcallback関数で受けてパースしたい
xxx.cpp
#include <nlohmann/json.hpp> 
using json = nlohmann::json;

void callback(const std_msgs::StringConstPtr& msg)
{
    std::cout << "params callback: " << msg->data << std::endl;

    auto s = msg->data;
    json j = json::parse(s);

    std::cout << j << std::endl;
}
  • ref

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?