Belle II Software  release-08-01-10
KeyValuePrinter Class Reference

create human-readable or JSON output for key value pairs. More...

#include <KeyValuePrinter.h>

Collaboration diagram for KeyValuePrinter:

Public Member Functions

 KeyValuePrinter (bool use_json, unsigned key_max_length=10)
 Ctor. More...
 
std::string string () const
 Return completed string.
 
template<class T >
void put (const std::string &key, const T &value)
 Add one key-value pair.
 
template<class T >
void put (const std::string &key, const std::map< std::string, T > &value)
 Specialization for map<>
 

Private Member Functions

std::string escape (const std::string &value) const
 escape string.
 
std::string escape (const char *value) const
 escape string literals.
 
template<class T >
std::string escape (const T &value) const
 escape numeric value.
 
template<class T >
std::string escape (const std::vector< T > &value) const
 escape vector<T>.
 
template<class T >
std::string escape (const std::map< std::string, T > &value) const
 escape map<string, T>.
 

Private Attributes

bool m_json
 create JSON output?
 
unsigned m_maxpad
 for human-readable output: how much padding after key?
 
std::string m_delim
 for JSON: comma to print after prev entry.
 
std::stringstream m_stream
 output being built.
 

Detailed Description

create human-readable or JSON output for key value pairs.

Usage example for human-readable output:

KeyValuePrinter pr(false); //JSON=false
pr.put("a", 123);
pr.put("bbbbb", "string");
pr.put("ccccccc", std::vector<std::string>({"string", "abc"}));
std::cout << pr.string();
//which prints
// a: 123
// bbbbb: string
// ccccccc: [string, abc]
KeyValuePrinter(bool use_json, unsigned key_max_length=10)
Ctor.

std::string, numeric types, std::vector<SUPPORTED TYPE>, and std::map<std::string, SUPPORTED TYPE> * are supported as value types for put().

JSON output is suitable for reading via e.g. json.loads() in Python, and performs the necessary escaping for strings. Compared to boost::property_tree::json_parser::write_json, KeyValuePrinter handles non-string types correctly.

Definition at line 46 of file KeyValuePrinter.h.

Constructor & Destructor Documentation

◆ KeyValuePrinter()

KeyValuePrinter ( bool  use_json,
unsigned  key_max_length = 10 
)
inlineexplicit

Ctor.

Parameters
use_jsontrue for JSON output, false for human-readable output.
key_max_lengthfor human-readable output, this should be equal to strlen(longest_key) for aligning values in output.

Definition at line 53 of file KeyValuePrinter.h.

53  :
54  m_json(use_json),
55  m_maxpad(key_max_length + 2),
56  m_delim("")
57  { }
unsigned m_maxpad
for human-readable output: how much padding after key?
bool m_json
create JSON output?
std::string m_delim
for JSON: comma to print after prev entry.

The documentation for this class was generated from the following files: