• Stars
    star
    1,082
  • Rank 42,777 (Top 0.9 %)
  • Language
    C++
  • License
    BSD 2-Clause "Sim...
  • Created almost 14 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

a header-file-only, JSON parser serializer in C++

PicoJSON - a C++ JSON parser / serializer

Copyright © 2009-2010 Cybozu Labs, Inc. Copyright © 2011-2015 Kazuho Oku

Licensed under 2-clause BSD license

Version

1.3.1-dev Build Status

Introduction

PicoJSON is a tiny JSON parser / serializer for C++ with following properties:

  • header-file only
  • no external dependencies (only uses standard C++ libraries)
  • STL-frendly (arrays are represented by using std::vector, objects are std::map)
  • provides both pull interface and streaming (event-based) interface

Reading JSON using the pull interface

There are several ways to use the pull (DOM-like) interface of picojson.

The easiest way is to use the two-argument parse function.

std::string json = "[ \"hello JSON\" ]";
picojson::value v;
std::string err = picojson::parse(v, json);
if (! err.empty()) {
  std:cerr << err << std::endl;
}

Four-argument parse function accepts a pair of iterators, and returns the end position of the input.

const char* json = "{\"a\":1}";
picojson::value v;
std::string err;
const char* json_end = picojson::parse(v, json, json + strlen(json), &err);
if (! err.empty()) {
  std::cerr << err << std::endl;
}
std::istream_iterator input(std::cin);
picojson::value v;
std::string err;
input = picojson::parse(v, input, std::istream_iterator(), &err);
if (! err.empty()) {
  std::cerr << err << std::endl;
}

It is also possible to use the >> operator to parse the input, however this interface is not thread-safe.

picosjon::value v;
std::cin >> v;
std::string err = picojson::get_last_error();

Accessing the values

Values of a JSON object is represented as instances of picojson::value class.

namespace picojson {

  class value {
    ...

  public:

    typedef std::vector<value> array;
    typedef std::map<std::string, value> object;

    value();                               // create a null object
    explicit value(bool b);                // create a boolean object
    explicit value(double n);              // create a number object
    explicit value(const std::string& s);  // create a string object
    explicit value(const array& a);        // create an array object
    explicit value(const object& o);       // create an "object"

    bool is<picojson::null>() const;       // check if the object is "null"

    bool is<bool>() const;                 // check if the object is a boolean
    const bool& get<bool>() const;         // const accessor (usable only if the object is a boolean)
    bool& get<bool>();                     // non-const accessor (usable only if the object is a boolean)

    bool is<double>() const;               // check if the object is a number
    const double& get<double>() const;     // const accessor (usable only if the object is a number)
    double& get<double>();                 // non-const accessor (usable only if the object is a number)

    bool is<std::string>() const;          // check if the object is a string
    const std::string& get<std::string>() const;
                                           // const accessor (usable only if the object is a string)
    std::string& get<std::string>();       // non-const accessor (usable only if the object is a string)

    bool is<array>() const;                // check if the object is an array
    const array& get<array>() const;       // const accessor (usable only if the object is an array)
    array& get<array>();                   // non-const accessor (usable only if the object is an array)

    bool is<object>() const;               // check if the object is an "object"
    const object& get<object>() const;     // const accessor (usable only if the object is an object)
    object& get<object>();                 // non-const accessor (usable only if the object is an array)

    bool evaluate_as_boolean() const;      // evaluates the object as a boolean

    std::string serialize() const;         // returns the object in JSON representation
    template void serialize(Iter os) const;
                                           // serializes the object in JSON representation through an output iterator

    std::string to_str() const;            // returns the object in string (for casual use)

  };

}

The code below parses a JSON string and prints the contents of the object.

picojson::value v;

// parse the input
std::cin >> v;
std::string err = picojson::get_last_error();
if (! err.empty()) {
  std::cerr << err << std::endl;
  exit(1);
}

// check if the type of the value is "object"
if (! v.is<picojson::object>()) {
  std::cerr << "JSON is not an object" << std::endl;
  exit(2);
}

// obtain a const reference to the map, and print the contents
const picojson::value::object& obj = v.get<picojson::object>();
for (picojson::value::object::const_iterator i = obj.begin();
     i != obj.end();
     ++i) {
  std::cout << i->first << ': ' << i->second.to_str() << std::endl;
}

Please note that the type check is mandatory; do not forget to check the type of the object by calling is<type>() before accessing the value by calling get<type>().

Reading JSON using the streaming (event-driven) interface

Please refer to the implementation of picojson::default_parse_context and picojson::null_parse_context. There is also an example (examples/streaming.cc) .

Serializing to JSON

Instances of the picojson::value class can be serialized in three ways, to ostream, to std::string, or to an output iterator.

picojson::value v;
...
std::cout << v;
picojson::value v;
...
std::string json = v.serialize();
picojson::value v;
...
v.serialize(std::ostream_iterator<char>(std::cout));

Experimental support for int64_t

Experimental suport for int64_t becomes available if the code is compiled with preprocessor macro PICOJSON_USE_INT64.

Turning on the feature will cause following changes to picojson:

  • new constructor picojson::value(int64_t) is defined
  • is<int64_t>() and get<int64_t>() become available
  • numerics in JSON within the bounds of int64_t and not using . nor e/E are considered as int64 type
  • the values are also avaliable as doubles as well (i.e. all values which are .is<int64_t>() == true are also .is<double>() == true)
  • int64 values are converted to double once get<double>() is called

Enabling the feature should not cause compatibility problem with code that do not use the feature.

Further reading

Examples can be found in the examples directory, and on the Wiki. Please add your favorite examples to the Wiki.

More Repositories

1

picoev

a tiny, lightning fast event loop for network applications
C
388
star
2

unco

undo any command
C
229
star
3

rat

NAT written in pure ruby
Ruby
172
star
4

jailing

super-easy chroot jail builder/runner for Linux
Perl
165
star
5

kaztools

shellscripts and utilities for myself
Perl
96
star
6

picohash

header-file-only implementation of various hash algorithms
C
89
star
7

Starlet

a Plack Server, formerly known as Plack::Server::Standalone::Prefork::Server::Starter
Perl
69
star
8

C

pseudo-interpreter of the C programming language (using GCC)
C
64
star
9

mysql_json

a MySQL UDF for handling JSON
C++
63
star
10

wpbench

benchmark the load timings of a web page
HTML
61
star
11

picogc

a tiny, portable, precise, mark-and-sweep GC in C++
C
57
star
12

p5-Server-Starter

a superdaemon for hot-deploying server programs
Perl
44
star
13

rangecoder

a fast range coder in C++, using SSE
C++
37
star
14

sha1.min.js

SHA-1 implementation in JavaScript (1480 bytes; intended for bookmarklets, etc.)
JavaScript
34
star
15

url_compress

a static PPM-based URL compressor / decompressor
Perl
34
star
16

cppref

man-style access to cppreference.com documents
Perl
32
star
17

mod_reproxy

X-Reproxy-URL header support for Apache/2.x
C
31
star
18

p5-http-parser-xs

a fast http parser
C
30
star
19

zson

binary JSON, compact and with support for streaming
JavaScript
28
star
20

p5-text-microtemplate

Text::MicroTemplate
Perl
24
star
21

mysql-ranking-engine

(to become) a MySQL storage engine specializing in ranking operation
C++
23
star
22

golombset

An implementation of Golomb compressed set in C
C
22
star
23

manymanythreads

A synthetic benchmark of C10K problem using pthreads or epoll
C
21
star
24

cosmic

fail-safe management tools for network-based software RAID, using mdadm + iSCSI
Perl
18
star
25

p5-test-mysqld

mysqld runner for tests
Perl
18
star
26

komake

A wrapper of make with sub-make concurrency limit
Perl
17
star
27

force-dedupe-git-modules

forcibly dedupe git-based NPM modules
JavaScript
16
star
28

p5-Net-DNS-Lite

pure-perl DNS resolver with support for timeout
Perl
16
star
29

p5-Class-Accessor-Lite

Perl
14
star
30

daifuku

transaction logging in JSON, within the MySQL database
Perl
14
star
31

p5-Parallel-Scoreboard

A scoreboard for monitoring status of many processes
Perl
14
star
32

blockdiff

differential backup tool for block devices and files
Perl
13
star
33

p5-test-httpd-apache2

Apache2 starter for testing perl modules
Perl
13
star
34

p5-Cache-LRU

a simple, fast implementation of an LRU cache in pure perl
Perl
12
star
35

p5-string-filter

Regexp-based structured text converter
Perl
12
star
36

kmyacc

http://www005.upp.so-net.ne.jp/kmori/kmyacc/
C
11
star
37

p5-parallel-prefork

Perl
11
star
38

picotemplate

a tiny template engine for embedded HTML
Perl
10
star
39

nopan

install software directly from SVN or Git (instead of from CPAN)
Perl
9
star
40

hq

C++
8
star
41

qhashmap

an open-addressing, linear-probing hash table, derived from v8/src/hashmap.h
C++
8
star
42

picostring

simple rope impl. using std::string
C++
8
star
43

add_with_overflow

an example that links LLVM bitcode and C++ with link-time optimization
C++
8
star
44

App-Restarter

restart command when files change
7
star
45

visiflate

a dumper for Deflate (RFC 1951); useful for visualizing the algorithm
C
7
star
46

git-pushdir

pushes the files in current directory to Git repository
Perl
7
star
47

h2-cache-digest

code snippets for h2-cache-digest
C
6
star
48

puby

6
star
49

draft-kazuho-httpbis-priority

Makefile
6
star
50

p5-test-postgresql

postgresql runner for tests
Perl
5
star
51

CGI-Application-Emulate-PSGI

a legacy-code-friendly PSGI adapter for CGI::Application
Perl
5
star
52

mprofile

http://developer.cybozu.co.jp/archives/kazuho/2009/07/mysql-539d.html
Perl
5
star
53

fakeiops

an LD_PRELOAD library for simulating storage systems with various IOPS
C
5
star
54

draft-kazuho-quic-quic-on-streams

Makefile
5
star
55

quic-perf-metrics

Makefile
5
star
56

ieee754.js

Pure-javascript decoder for IEEE 754 floating point numbers
JavaScript
4
star
57

japanize.firefox

Firefox plugin for Japanize
JavaScript
4
star
58

incline

replicator for RDB shards
C++
4
star
59

friendsd

server of the `friends` program, used at komaba.ecc.u-tokyo.ac.jp from 1996 to 1999
4
star
60

benchart

Minimalistic benchmark logger and visualizer
Perl
3
star
61

p5-Sub-Throttle

Perl
3
star
62

SQL-QueryMaker

helper functions for SQL query generation
Perl
3
star
63

Plack-Middleware-AddDefaultCharset

port of Apache2's AddDefaultCharset
Perl
3
star
64

bindlocal

an LD_PRELOAD library that forces servers to listen on 127.0.0.1 instead of 0.0.0.0
C
3
star
65

esDateParser

a date parser compliant to ECMA 262, derived from V8
C++
3
star
66

p5-Sub-Timekeeper

calls a function with a stopwatch
Perl
3
star
67

Test-Mocha-PhantomJS

JavaScript
3
star
68

examples

code snippets
C
3
star
69

kazuho.github.com

HTML
2
star
70

draft-kazuho-quic-authenticated-handshake

Authenticated Handshake for QUIC (using ESNI)
Makefile
2
star
71

p5-DBIx-Printf

A printf-style prepared statement
Perl
2
star
72

aobench.jsx

original: http://kioku.sys-k.net/aobench_jsx/
JavaScript
2
star
73

draft-kazuho-quic-address-bound-token

Makefile
2
star
74

gh-fetch-submodules

fetch the missing submodule contents within a GitHub release tarball
Perl
2
star
75

kazutils.c

tiny set of C functions
1
star
76

myfirst-usdt

learning userspace DTrace
Makefile
1
star
77

early-hints

now part of https://github.com/httpwg/http-extensions
Makefile
1
star
78

net.examp1e.picoorm

Java
1
star
79

picoshparser

(experimental) parser of Structured Headers
C
1
star
80

force-dedupe-git-modules.m2

test repo for https://github.com/kazuho/force-dedupe-git-modules
JavaScript
1
star
81

draft-kazuho-httpbis-selftrace

Makefile
1
star
82

force-dedupe-git-modules.m1

test repo for https://github.com/kazuho/force-dedupe-git-modules
JavaScript
1
star
83

protected-sni

Makefile
1
star
84

http-cache-fingerprint

cache fingerprint header for HTTP
Makefile
1
star