Compact lib for JSON parsing (cross-platform C++)

Recently i was in search of compact C++ source code for parsing  of JSON format. This is very simple minimalistic format and its very popular – but i was surprised when found a lot of complex parsers and no simple implementation inside one cpp-h pair. So i wrote one.

mvjsonlogo

Here it is – tiny C++ cross-platform solution for JSON decoding without any dependencies like boost or something: MVJSON.cpp MVJSON.h (version 1.0)

UPD: recent version could be found here: GIST

As example of usage here is real sample of weather forecast from openweathermap.org (by the way it happened to be very nice weather forecast site with nice api). Sample of JSON data:

The example of decoding part:

using namespace JSON;

MVJSONReader reader(jsonText);

if (reader.root != NULL)

{

    MVWeatherPoint* point = new MVWeatherPoint();

    if (reader.root->hasField(“sys”))

    {

        point->sunrize = reader.root->getField(“sys)->getFieldInt(“sunrise”);

        point->sunset = reader.root->getField(“sys”)->getFieldInt(“sunset”);

        point->location = reader.root->getFieldString(“name”);

        point->temp = reader.root->getField(“main”)->getFieldDouble(“temp”) – 273.15;

        point->pressure = reader.root->getField(“main”)->getFieldDouble(“pressure”);

        point->humidity = reader.root->getField(“main”)->getFieldDouble(“humidity”);

        point->windSpeed = reader.root->getField(“wind”)->getFieldDouble(“speed”);

        point->clouds = reader.root->getField(“clouds”)->getFieldDouble(“all”);

        if (reader.root->getField(“weather”) != NULL)

            if (reader.root->getField(“weather”)->size() > 0)

            {

                // we take only first element from list

                point->weatherId = reader.root->getField(“weather”)->at(0)->getFieldInt(“id”);

                point->icon = reader.root->getField(“weather”)->at(0)->getFieldString(“icon”);

                point->description = reader.root->getField(“weather”)->at(0)->getFieldString(“description”);

            }

    }

}

 

You can explore source code and find that parsing is made rather compact way – recurrent processing of strings. It is not the fastest way, but it is fast enough. Lib has only stdlib dependence.

Current version is only for reading utf-8. And special encoding “\u four-hex-digits” is not implemented.

Licence: feel free to use it (with no warranty). Any suggestions / improvements / bugfixes are welcome in comments.