User Tools

Site Tools


nlohmann JSON handle sample

json.cpp
/*
 * json.cpp
 *
 * Copyright 2019 Oleg Borodin  <borodin@unix7.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 *
 *
 */
 
 
#include <iostream>
#include <fstream>
#include <nlohmann/json.hpp>
 
int main(int argc, char **argv) {
 
    std::string s =
        R"({
          "pi": 3.141,
          "happy": true,
          "name": "Niels",
          "nothing": null,
          "answer": {
            "everything": 42
          },
          "list": [1, 0, 2],
          "object": {
            "currency": "USD",
            "value": 42.99
          }
        })";
    auto j = nlohmann::json::parse(s);
 
    std::cout << j["answer"]["everything"] << std::endl;
    std::cout << j["list"] << std::endl;
 
    std::cout << j["object"] << std::endl;
 
    auto obj = j["object"];
    std::cout << obj << std::endl;
 
 
    for (auto& x: j["list"]) {
        std::cout << x << std::endl;
    }
 
    auto list = j["list"];
    for (auto& x: list) {
        std::cout << x << std::endl;
    }
 
    std::ofstream o("pretty.json");
    o << std::setw(4) << j << std::endl;
 
 
    return 0;
}
$ c++ -Wall -I/usr/local/include -o json json.cpp
$ ./json
42
[1,0,2]
{"currency":"USD","value":42.99}
{"currency":"USD","value":42.99}

1
0
2

1
0
2