Thursday, November 14, 2019

JSON for modern C++

//https://github.com/nlohmann/json

#include <iostream>
#include <iomanip>
#include <nlohmann/json.hpp>
#include <fstream>

using json = nlohmann::json;

int main() {
    // a JSON text
    char text[] = R"(
     {
         "Image": {
             "Width":  800,
             "Height": 600,
             "Title":  "View from 15th Floor",
             "Thumbnail": {
                 "Url":    "http://www.example.com/image/481989943",
                 "Height": 125,
                 "Width":  100
             },
             "Animated" : false,
             "IDs": [116, 943, 234, 38793]
         },
        "Image1": {
             "Width":  800,
             "Height": 600,
             "Title":  "View from 15th Floor",
             "Thumbnail": {
                 "Url":    "http://www.example.com/image/481989943",
                 "Height": 125,
                 "Width":  100
             },
             "Animated" : false,
             "IDs": [116, 943, 234, 38793]
         }
     }
     )";

    // parse and serialize JSON
    json j_complete = json::parse(text);
    //std::cout << std::setw(4) << j_complete << "\n\n";

    //std::ifstream ifs("States.json");
    //json j = json::parse(ifs);
    //std::cout << std::setw(4) << j << "\n\n";

    for (const auto &item : j_complete.items()) {
        std::cout << item.key() << "\n";
        if(item.key() == "Image"){
            std::cout << "!!!!!!!!!!!!!!\n";
        }

        for (const auto &val : item.value().items()) {
            std::cout << "  " << val.key() << ": " << val.value() << "\n";
            if(val.key() == "Thumbnail"){
                for(const auto &xx : val.value().items()){
                    if(xx.key() == "Url"){
                        std::cout << "*****************\n";
                    }
                }
                std::cout << "================\n";
            }
            if(val.value() == 800){
                std::cout << "XXXXXXXXXXXXXX\n";
            }
        }

    }
}

No comments: