IAM

OPENSOURCEFAN STUDYING
STUDYINGCOMPUTERSCIENCEANDMATH COMPUTERSCIENCE

Check out the latest superpixel benchmark — Superpixel Benchmark (2016) — and let me know your opinion! @david_stutz
07thJANUARY2017

SNIPPET

C++

Example of using JSONCpp for reading/writing JSON files.

main.json
// Configuration options
{
    // Default encoding for text
    "encoding" : "UTF-8",
    
    // Plug-ins loaded at start-up
    "plug-ins" : [
        "python",
        "c++",  // trailing comment
        "ruby"
        ],
        
    // Tab indent size
    // (multi-line comment)
    "indent" : { /*embedded comment*/ "length" : 3, "use_space": true }
}
main.cpp
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include <json/json.h>

int main(int argc, char** argv) {

    Json::Value root;
    Json::Reader reader;
    
    std::ifstream jsonFile("main.json", std::ifstream::in | std::ifstream::binary);
    reader.parse(jsonFile, root, false); // True for collecting comments
    
    std::string encoding = "";
    if (root.isMember("encoding")) {
        encoding = root["encoding"].asString();
    }
    
    std::vector<std::string> plugIns;
    if (root.isMember("plug-ins"))
    {
        for (int i = 0; i < root["plug-ins"].size(); i++)
        {
            plugIns.push_back(root["plug-ins"][i].asString());
        }
    }
    
    int indent_length = 0;
    bool indent_use_space = false;
    if (root.isMember("indent"))
    {
        if (root["indent"].isMember("length"))
        {
            indent_length = root["indent"]["length"].asInt();
        }
        
        if (root["indent"].isMember("use_space"))
        {
            indent_use_space = root["indent"]["use_space"].asBool();
        }
    }
    
    std::cout << "Encoding: " << encoding << std::endl;
    
    std::cout << "PlugIns: ";
    for (unsigned int i = 0; i < plugIns.size(); i++)
    {
        std::cout << plugIns[i];
        
        if (i < plugIns.size() - 1)
        {
            std::cout << ",";
        }
    }
    std::cout << std::endl;
    
    std::cout << "Indent:" << std::endl;
    std::cout << "\tLength: " << indent_length << std::endl;
    std::cout << "\tUse space: " << indent_use_space << std::endl;
    return 0;
}

What is your opinion on the code snippet? Is it working? Let me know your thoughts in the comments below or using the following platforms: