物理の駅 Physics station by 現役研究者

テクノロジーは共有されてこそ栄える

テキストファイルの読み取りと、JSONファイルの書き出し・読み取り方

picojson.h は https://github.com/kazuho/picojson/blob/master/picojson.h からダウンロードすべし。

#include "picojson.h"
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>

//テキストファイルの読み取り
inline std::string read_txt(std::string const& path)
{
    std::ifstream ifs(path);
    std::stringstream buffer;
    buffer << ifs.rdbuf();
    std::string str = buffer.str();
    // UTF-8のBOM付きをチェック
    if (str.size() >= 3 && str[0] == -17 && str[1] == -69 && str[2] == -65)  return str.substr(3);
    else  return str;
}


//picojson::object型でJSONファイルの読み取り
picojson::object read_json_obj(std::string path)
{
    std::ifstream ifs(path);
    if (!ifs)
    {
        throw std::exception("File cannot be opened.");
    }

    std::string json = read_txt(path);
    picojson::value val;
    std::string err;
    picojson::parse(val, json.c_str(), json.c_str() + strlen(json.c_str()), &err);
    if (!err.empty())
    {
        throw std::exception("JSON format error in");
    }
    return val.get<picojson::object>();
}

//読み取りのサンプル
void read_sample()
{
    auto obj = read_json_obj("file.json");
    auto nog = obj.at("Nogs").get<picojson::array>();
    for (int j = 0; j < nog.size(); j++)
    {
        std::cout << nog[j].get<double>() << " ";
    }
    std::cout << std::endl;
}

//書き出しのサンプル
void write_sample() {
    picojson::object obj;
    picojson::array arr;
    arr.emplace_back(picojson::value(1.0));
    arr.emplace_back(picojson::value(2.0));
    arr.emplace_back(picojson::value(3.0));
    obj["Nogs"] = picojson::value(arr);
    std::ofstream ofs("file.json");
    ofs << picojson::value(obj).serialize(true) << std::endl;
}

//書き出しのサンプル 配列版
void write_sample2() {
    picojson::array arr;
    arr.emplace_back(picojson::value(1.0));
    arr.emplace_back(picojson::value(2.0));
    arr.emplace_back(picojson::value(3.0));
    std::ofstream ofs("file_arr.json");
    ofs << picojson::value(arr).serialize(true) << std::endl;
}

int main() {
    write_sample();
    read_sample();
    return 0;
}

こういう内容のファイルが読み書きされる

{
  "Nogs": [
    1,
    2,
    3
  ]
}

期待される出力

1.00000 2.00000 3.00000

デバッグしてないので取り扱いに注意して下さい。

メンバーが存在しているかの確認は、find()を使って行うと良い。

if (input.find("member") != input.end()) {
    std::cout << "find" << std::endl;
}
else {
    std::cout << "not find" << std::endl;
}