Json in D: clean, simple API
Adam D. Ruppe via Digitalmars-d
digitalmars-d at puremagic.com
Thu May 11 13:36:13 PDT 2017
On Thursday, 11 May 2017 at 20:22:22 UTC, aberba wrote:
> With that i meant designing of a simple-clean api
my jsvar.d works kinda similarly to javascript... though i
wouldn't call it "clean" because it will not inform you of
missing stuff.
jsvar.d is here:
https://raw.githubusercontent.com/adamdruppe/arsd/master/jsvar.d
---
// dmd test.d jsvar.d
import arsd.jsvar;
import std.stdio;
void main() {
// reading json with `var.fromJson`
var obj = var.fromJson(`{"a":{"b":10},"c":"hi"}`);
// inspecting contents
writeln(obj.a);
writeln(obj.a.b);
writeln(obj.c);
// convert to basic static type with `.get!T`
string c = obj.c.get!string;
// change the contents with dot notation
obj.a = 15;
obj.d = "add new field too";
writeln(obj);
struct Test {
int a;
string c;
}
// can even get plain structs out
Test test = obj.get!Test;
writeln(test);
// and set structs
test.c = "from D";
obj = test;
writeln(obj);
// writeln on an object prints it in json
// or you can explicitly do
writeln(obj.toJson());
// big thing is referencing non-existent
// things is not an error, it just propagates null:
writeln(obj.no.such.property); // null
// but that can be convenient
}
---
More information about the Digitalmars-d
mailing list