从.txt文件中将C 中的JSON字符串贴上
Prettify a JSON string in C++ from a .txt file
我当前在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:%un", 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:%sn", 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。
使用产生字符串的转储
int indent = 4;
nlohmann::json data;
data.dump(indent);
或使用带有场宽度集的流输出过载
std::ofstream o("pretty.json");
o << std::setw(4) << data << std::endl;
相关文章:
- 如何在 c++ 非托管代码中反序列化 byte[] 的 json 字符串?
- 使用 minijson-reader 库读取 JSON 字符串时出现问题
- POCO C++对象到 JSON 字符串序列化
- 将可变参数模板参数转换为 JSON 字符串
- 从 json 字符串将 QVariant 转换为 QList<MyClass>
- 如何使用 boost 属性树来解析 boost 中 json 字符串中的数组中的元素?
- 使用Python将C 结构更改为JSON字符串
- 如何将变量用作原始 JSON 字符串中的数据?
- 如何将 JsonObject 转换为 JSON 字符串
- 从.txt文件中将C 中的JSON字符串贴上
- 使用 Cereal 反序列化 JSON 字符串
- 使用 jsoncpp 解析 JSON 字符串
- Rapidjson漂亮的打印使用JSON字符串作为作者的输入
- 如何处理JSON字符串中的unicode值
- 为什么BOOST创建的JSON字符串与我的服务器所需的不同
- 如何在C++中使用boost库将类对象转换为json字符串
- 如何在使用JSON boost序列化创建JSON字符串时获取名称-值对
- 如何在网络上序列化并发送JSOn字符串中的std::list
- 将带有 json 字符串的帖子发送到服务器
- 使用 Casablanca REST SDK 将 JSON 字符串转换为C++对象