Chinese Yellow Pages | Classifieds | Knowledge | Tax | IME

nlohmann::json is a popluar json lib.

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

document at: https://nlohmann.github.io/json/doxygen/index.html

 

sample code:

#include <iostream>
2 #include <nlohmann/json.hpp>
3
4 using json = nlohmann::json;
5
6 int main()
7 {
8  // create a JSON object with different entry types
9  json j =
10  {
11  {“integer”, 1},
12  {“floating”, 42.23},
13  {“string”, “hello world”},
14  {“boolean”, true},
15  {“object”, {{“key1”, 1}, {“key2”, 2}}},
16  {“array”, {1, 2, 3}}
17  };
18
19  // access existing values
20  int v_integer = j.value(“integer”, 0);
21  double v_floating = j.value(“floating”, 47.11);
22
23  // access nonexisting values and rely on default value
24  std::string v_string = j.value(“/nonexisting”_json_pointer, “oops”);
25  bool v_boolean = j.value(“nonexisting”, false);
26
27  // output values
28  std::cout << std::boolalpha << v_integer << ” “ << v_floating
29  << ” “ << v_string << ” “ << v_boolean << “\n”;
30 }

 

There are several ways to for value access :

value access

in addtion,  there are: jsonobj.at(“key”),   jsonobj[“key”] etc  . quite confusing if you r newbie,

Here is the document:

.value():

Unlike at(const typename object_t::key_type&), this function does not throw if the given key key was not found.

Unlike operator[](const typename object_t::key_type& key), this function does not implicitly add an element to the position defined by key. This function is furthermore also applicable to const objects.