ヘッダー
#include <picojson.h> // あるファイルの情報を読み取り std::string read_txt(std::string filepath) { // ファイルの最初のbyteから最後のbyteまで読み取り std::string str((std::istreambuf_iterator<char>(std::ifstream(filepath))), std::istreambuf_iterator<char>()); if (str.size() < 3) { return str; } // UTF-8のBOM付きをチェック if (str[0] == -17 && str[1] == -69 && str[2] == -65) { return str.substr(3); } else { return str; } } //array型のJSONファイルの読み取り picojson::array read_json_arr(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"); } picojson::array &obj = val.get<picojson::array>(); return obj; }
こういうファイルを読み取りたい
[ { "Nogs": [ [ 1.0, 2.0, 3.0 ] ] } ]
読み取り例
void sample() { auto arr = read_json_arr("file.json"); for (int i = 0; i < arr.size(); i++) { auto obj = arr[i].get<picojson::object>(); auto nog = obj.at("Nogs").get<picojson::array>()[0].get<picojson::array>(); for (int j = 0; j < nog.size(); j++) { std::cout << nog[j].get<double>() << " "; } std::cout << std::endl; } }
期待される出力
1.00000 2.00000 3.00000
デバッグしてないので取り扱いに注意して下さい。