私は現在C ++で作業しており、ostreamを使用して.txtファイルに書き込む要求からHTTP応答を取得しています。これは非同期で発生するため、これを変更したくありません。
データの書き込みが終わったら、ファイルから読み取りたい
{"data":{"request":[{"type":"City","query":"London, United Kingdom"}],"weather":[{"date":"2013-04-21","astronomy".....
〜どういうわけか〜nlohmann / jsonなどの外部ライブラリまたはother(?)を使用して文字列をプリティフィケーションし、次に
a)コンソールに出力し、b)別のファイル(pretty.json)に保存します
https://github.com/nlohmann/jsonから使用する方法を理解するのに問題があります
これにアプローチする方法はありますか?
EOFを一種の「バッファー」にヒットするまでファイルを1行ずつ取得し、その上で_jsonを実行して、コンソールに表示できるソリューションを保存することを考えていました...
これまでの私のコード
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
#include <iostream>
#include <sstream>
#include "json.hpp"
using namespace utility; // string conversion
using namespace web; // URI
using namespace web::http; // HTTP commands
using namespace web::http::client; // HTTP Client features
using namespace concurrency::streams; // Asynch streams, like Node
using json = nlohmann::json;
int main()
{
auto fileStream = std::make_shared<ostream>();
// Open stream to output file.
pplx::task<void> requestTask = fstream::open_ostream(U("results.txt"))
.then([=](ostream outFile)
{
*fileStream = outFile;
http_client client //gets the info
return client.request(methods::GET, stringBuilder.to_string());
})
.then([=](http_response response) // set up response handler
{
printf("Received response status code:%u\n", response.status_code());
return response.body().read_to_end(fileStream->streambuf());
})
.then([=](size_t) // close file stream
{
return fileStream->close();
})
.then([=]()
{
nlohmann::json j;
std::ifstream i;
i.open("results.txt"); // ?? <<< === this is where my question is
});
// Wait for all the outstanding I/O to complete, handle exceptions
try
{
requestTask.wait();
}
catch (const std::exception &e)
{
printf("Error exception:%s\n", e.what());
}
return 0;
}
解決:
.then([=]()
{
// read a JSON file
std::ifstream readFromFile("results.txt");
if (readFromFile.is_open()) {
nlohmann::json j;
readFromFile >> j;
// write prettified JSON to another file
std::ofstream writeToFile("pretty.json");
writeToFile << std::setw(4) << j << std::endl;
readFromFile.close();
writeToFile.close();
}
else {
std::cout << "unable to open file";
}
});
nlohmannでかわいがるには2つの選択肢があります。
文字列を生成するダンプを使用します
int indent = 4;
nlohmann::json data;
data.dump(indent);
または、フィールド幅を設定してストリーム出力オーバーロードを使用します
std::ofstream o("pretty.json");
o << std::setw(4) << data << std::endl;
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加