2017-12-15 75 views
0

現在、C++で作業していますが、ostreamを使用して.txtファイルに書き込む要求からHTTP応答を取得しています。これは非同期的に起こり、私はこれを変更したくありません。C++のJSON文字列を.txtファイルから整形する

データが書き込まれて実行されると、私はファイルから

{"data":{"request":[{"type":"City","query":"London, United Kingdom"}],"weather":[{"date":"2013-04-21","astronomy".....

を読みたい〜何とか〜外nlohmann/JSONのようなライブラリまたは他のいずれかを使用して文字列を飾り立てる(?)して、

A)(pretty.json)

)コンソールと Bにそれを印刷し、別のファイルに保存し、私はから使用する方法、トラブルの理解を持っています: https://github.com/nlohmann/json

これにアプローチする方法はありますか?私のコード

私は「バッファ」の一種にEOFを打つまで、行毎にファイルを取得し、その上_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; 
} 

SOLUTION:

.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"; 
    } 

}); 

答えて

2

次の2つの選択肢のを持っていますnlohmannと賛美する。

は、文字列

int indent = 4; 
nlohmann::json data; 
data.dump(indent); 

またはフィールド幅のストリーム出力の過負荷を使用するには

std::ofstream o("pretty.json"); 
o << std::setw(4) << data << std::endl; 
を設定生成ダンプを使用します
関連する問題