yajl

YAJL, Yet Another JSON library, binding for D.


Keywords
library, data
Licenses
BSL-1.0/SSPL-1.0
Install
dub fetch yajl --version 0.2.0

Documentation

YAJL binding for D

yajl-d is a YAJL binding for D.

yajl-d is based on YAJL and work on 2.1.0 or later.

Install

Add yajl to dependencies of package.json.

  "dependencies": {
    "yajl": ">=0.2.0"
  }

Run example

Need to link yajl library

dmd -Isrc src/**/*.d -L-lyajl -run example/encode_bench.d

Usage

Encode

  • yajl.encode(value) / yajl.encode(value, opt)
import yajl;

struct Hoge
{ 
    ulong id;
    string word;
    bool yes; 
}

// {"id":100,"word":"hey!","yes":true}
string json = encode(Hoge(100, "hey!", true));

Decode

  • yajl.decode(value) / yajl.decode(value, opt)
import yajl;

Hoge hoge = decode!Hoge(`{"id":100,"word":"hey!","yes":true}`);
  • yajl.decoder.Decoder

Use decode and decodedValue methods.

import yajl.decoder;

Decoder decoder;
if (decoder.decode(`{"id":100,"word":"hey!","yes":true}`) {
    Hoge hoge = decoder.decodedValue!Hoge;
    // ...
}

Decoder#decode is a straming decoder, so you can pass the insufficient json to this method. If Decoder#decode can't parse completely, Decoder#decode returns false.

Encoder.Option and Decoder.Option

encode and decode can take each Option argument. If you want to know more details, see unittest of yajl.encoder / yajl.decoder.

Set callback to detect missing field

You can set own callback to Decoder.Option.missingHandler. Here is an example:

import yajl;
import std.stdio;

struct Test
{
  string name;
  int age;
}

void main()
{
  auto test = Test("Bob", 20);
  auto encoded = `{ "name": "Bob", "age": 20}`;
  auto missing = `{ "name": "Bob"}`;

  Decoder.Option opt;
  opt.missingHandler = (string field) { writeln(field); };
  writeln(decode!Test(encoded, opt));
  writeln(decode!Test(missing, opt)); // Callback called with missing field
}

Using a D keyword in JSON field names

Since a field name cannot be a D keyword, for example body or out, the variable and JSON field must have separate names. For this, use the @JSONName("name") attribute:

import yajl;

struct Hoge
{ 
    ulong id;
    @JSONName("body") string _body;
    bool yes; 
}

// {"id":100,"body":"hey!","yes":true}
string json = encode(Hoge(100, "hey!", true));

Perfomance

D: dmd 2.066.0
yajl: 2.1.0
OS: Mac OS X ver 10.9
CPU: 2.6 GHz Intel Core i7

encode(QPS) multi encode(QPS) decode(QPS) multi decode(QPS)
std.json 262272 Not supported 287072 Not supported
yajl-d 700098 948965 514065 775532

Benchmark code can be found in the example directory.

TODO

  • Limited direct conversion decoding
  • Test on Windows

Link

Copyright

Author Masahiro Nakagawa
Copyright Copyright (c) 2013- Masahiro Nakagawa
License Boost Software License, Version 1.0