用.txt文件在C ++中整理JSON字符串

问题描述 投票:0回答:1

我目前正在使用C ++,从使用ostream写入.txt文件的请求中获取HTTP响应。这是异步发生的,我不想改变它。

一旦完成数据写入,我想从文件中读取

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

〜不知何故〜使用像nlohmann / json这样的外部库或其他(?)来预处理字符串

a)将其打印到控制台,b)将其保存在不同的文件中(pretty.json)

我无法理解使用哪种方法: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";
    }

 });
c++ json asynchronous nlohmann-json
1个回答
3
投票

你有两种选择用nlohmann来美化。

使用dump生成一个字符串

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

或者使用流输出重载并设置字段宽度

std::ofstream o("pretty.json");
o << std::setw(4) << data << std::endl;
© www.soinside.com 2019 - 2024. All rights reserved.