2017-12-15 1 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; 
} 

해결책 :

.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

당신은 두 가지 선택에있다 nlohmann으로 prettify.

문자열을

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

을 생산 또는

std::ofstream o("pretty.json"); 
o << std::setw(4) << data << std::endl; 
설정 필드 폭 스트림 출력 과부하를 사용하여 덤프를 사용
관련 문제