下記環境で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