LoginSignup
0
2

More than 1 year has passed since last update.

ros json c++

Last updated at Posted at 2022-02-01

はじめに

ros c++ パッケージでjsonを扱うためのメモ

※追記(2022/12/25): こっちのライブラリのほうが使いやすい

install

sudo apt install rapidjson-dev

プログラム

CMakeLists.txt
cmake_minimum_required(VERSION 3.0.2)
project(json_samples)

include_directories(include/rapidjson/include) ## add

find_package(catkin REQUIRED)

catkin_package(
)

## add
add_executable(main src/main.cpp) 
target_link_libraries(main 
)
src/main.cpp
#include <fstream>
#include <iostream>

#include "rapidjson/document.h"
#include "rapidjson/istreamwrapper.h"
#include "rapidjson/ostreamwrapper.h"
#include "rapidjson/writer.h"

using namespace rapidjson;

int main(int, char **)
{

    // read file
    std::ifstream ifs("sample.json");
    IStreamWrapper isw(ifs);

    Document doc;
    doc.ParseStream(isw);

    std::cout << "a: " << doc["a"].GetInt() << std::endl;
    std::cout << "b: " << doc["b"].GetInt() << std::endl;
    std::cout << "c: " << doc["c"].GetInt() << std::endl;
    std::cout << " ---- " << std::endl;

    // change value
    doc["a"].SetInt(7); 

    std::cout << "a: " << doc["a"].GetInt() << std::endl;
    std::cout << "b: " << doc["b"].GetInt() << std::endl;
    std::cout << "c: " << doc["c"].GetInt() << std::endl;

    // write file
    std::ofstream ofs("output.json");
    OStreamWrapper osw(ofs);

    Writer<OStreamWrapper> writer(osw);
    doc.Accept(writer);    
}

実行

実行ディレクトリに以下のような,jsonファイルを用意します

sample.json
{
  "a":1,
  "b":2,
  "c":3
}

実行するとsample.jsonを読み込んでoutput.jsonというファイルに値変更したjsonデータが保存されます.

$ rosrun json_samples main
a: 1
b: 2
c: 3
 ---- 
a: 7
b: 2
c: 3
$ cat output.json
{"a":7,"b":2,"c":3}

参考

リポジトリ

0
2
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
0
2