Skip to content

c++ JSON parser based on std::any container (c++17)

License

Notifications You must be signed in to change notification settings

ggaudeau/anyjson

Repository files navigation

anyjson

C++ JSON parser / stringifier based on STL (c++17)

API

namespace anyjson {
  using Value   = std::any;
  using Object  = std::map<std::string, Value>;
  using Array   = std::vector<Value>;
  using String  = std::string;
  using Number  = double;
  using Boolean = bool;
  using Null    = std::nullptr_t;

  Value parse(std::istream&);
  bool stringify(const Value&, std::ostream&);
}

As its repository name indicates, main object used to store JSON data is std::any. So that only recent compilers like g++-7 or greater can build this source code.

  • no dependency except the STL
  • template method to() that converts std::any to other types
  • print traces in debug mode
  • usable in multithreaded program

Usage

#include <sstream>
#include "anyjson.hpp"
#include "anyjson_tools.hpp" // to()

int main()
{
  std::stringstream iss("{ \"item\": { \"value\": 0 } }");
  std::any&& data = anyjson::parse(iss);
  
  if (data.has_value()) {
    try {
      anyjson::Object& root = to<anyjson::Object&>(data);
      anyjson::Object::iterator rootIt = root.find("item");

      if (rootIt != root.end()) {
        anyjson::Object& item = to<anyjson::Object&>(rootIt->second);
	    anyjson::Object::iterator itemIt = item.find("value");

        if (itemIt != item.end()) {
          anyjson::Number& value = to<anyjson::Number&>(itemIt->second);

          value = 42;
        }
      }

	} catch (const std::exception& e) {
	  std::cerr << e.what() << std::endl;
	}

	if (anyjson::stringify(data, std::cout)) {
	  std::cout << std::endl;
	  return 0;
	}	
  }
  return 1;
}

Limitations

  • stringify offers only the compact format (no whitespace)
  • stringigy uses type comparaison to unstack std::any variable

Tested on Ubuntu 20.04, g++ 9.3

About

c++ JSON parser based on std::any container (c++17)

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published