Header only CPP JSON library picojson

Tried a nice JSON library for C++ @ https://github.com/kazuho/picojson.

Json:

{
  "hoge": 12.3,
  "page": true,
  "piyo": "piyopiypo",
  "ar": [
    1,2,3,4,5
  ],
  "ar2": [
    {
      "foo": "foo string",
      "bar": 12345.6
    },
    {
      "foo": "foo2 string",
      "bar": 78.99
    }
  ]
}

Test:

#include "pre.h"
pre.h ***
#define __STDC_WANT_LIB_EXT1__ 1

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <iostream>
#include <boost/format.hpp>

#define PICOJSON_USE_INT64
#include "deps/picojson.h"

main.cpp ***
#include "pre.h"

using namespace std;

int main(int argc, char const *argv[]) {
  printf("* started.\n");

  picojson::value json;
  cin >> json;

  picojson::object& o = json.get<picojson::object>();
  int hoge = o["hoge"].get<double>();
  bool page = o["page"].get<bool>();
  string piyo = o["piyo"].get<string>();

  cout << boost::format("hoge: %d\n") % hoge;
  cout << boost::format("page: %d\n") % page;
  cout << boost::format("piyo: %s\n") % piyo;

  picojson::array ar = o["ar"].get<picojson::array>();
  for (picojson::array::iterator it = ar.begin(); it != ar.end(); it++)
  {
    cout << boost::format("ar item: %d\n") % it->get<int64_t>();
  }

  picojson::array ar2 = o["ar2"].get<picojson::array>();
  for (picojson::array::iterator it = ar2.begin(); it != ar2.end(); it++)
  {
    picojson::object& item = it->get<picojson::object>();
    cout << boost::format("foo: %s\n") % item["foo"].get<string>();
    cout << boost::format("bar: %f\n") % item["bar"].get<double>();
  }

  printf("* completed.\n");
}

Leave a Reply

Your email address will not be published. Required fields are marked *