Skip to content

Instantly share code, notes, and snippets.

@vinniefalco
Created November 15, 2019 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vinniefalco/f2914abb45500e6d1bca33ab528d870a to your computer and use it in GitHub Desktop.
Save vinniefalco/f2914abb45500e6d1bca33ab528d870a to your computer and use it in GitHub Desktop.
//
// Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/vinniefalco/json
//
/*
This example parses a JSON file and pretty-prints
it to standard output.
*/
#include <boost/json.hpp>
#include <fstream>
#include <iostream>
namespace json = boost::json;
json::value
parse(std::istream& is)
{
json::parser p;
json::error_code ec;
p.start();
auto const exceptions = is.exceptions();
is.exceptions(std::ios_base::iostate::
do
{
char buf[4096];
is.read(buf, sizeof(buf));
auto const n = is.gcount();
p.write(buf, n, ec);
if(ec)
throw json::system_error(ec);
}
while(! is.eof());
p.write_eof(ec);
if(ec)
throw json::system_error(ec);
return p.release();
}
void
pretty_print(
int
main(int argc, char** argv)
{
if(argc != 2)
{
std::cerr <<
"Usage: pretty <filename>"
<< std::endl;
return EXIT_FAILURE;
}
try
{
// Open the file
std::ifstream ifs(argv[1]);
ifs.exceptions(
// Parse the file as JSON
auto const jv = parse(ifs);
// Now pretty-print the value
pretty_print(std::cout, jv);
}
catch(std::exception const& e)
{
std::cerr <<
"Caught exception: "
<< e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment