On Thursday, 15 January 2015 at 12:50:59 UTC, Rikki Cattermole
wrote:
On 16/01/2015 1:37 a.m., anonymous wrote:
On Thursday, 15 January 2015 at 12:10:09 UTC, Rikki Cattermole
wrote:
On 16/01/2015 12:16 a.m., anonymous wrote:
what's the right syntax for building a JSON tree ? I try to
do like in
an AA but the program throw because the Key doesn't exist:
---
import std.stdio, std.json;
void main(string[] args)
{
struct Foo{
string a, b;
void writeToJson(ref JSONValue target) {
target["a"] = JSONValue(a);
target["b"] = JSONValue(b);
}
}
JSONValue root = parseJSON("{}");
root["items"] = JSONValue([""]);
Foo*[] foos;
foos ~= new Foo("a1","b1");
foos ~= new Foo("a2","b2");
foreach(foo; foos) {
root["items"].array.length += 1;
root["items"].array[$-1] = parseJSON("{}");
foo.writeToJson(root["items"].array[$-1]);
}
}
---
import std.stdio, std.json;
void main(string[] args)
{
struct Foo{
string a, b;
void writeToJson(ref JSONValue target) {
target["a"] = JSONValue(a);
target["b"] = JSONValue(b);
}
}
JSONValue root = ["items": cast(string[])[]];
Foo[] foos;
foos ~= Foo("a1","b1");
foos ~= Foo("a2","b2");
foreach(foo; foos) {
root["items"].array ~= JSONValue(foo.a);
root["items"].array ~= JSONValue(foo.b);
}
writeln(root.toString());
}
I would recommend keeping away from std.json. Its an old
piece of
code, that needs to be replaced.
Vibe.d has a much nicer implementation that is really decent.
I would
recommend that, if you are up to using the build manager dub.
Thx, but actually I initially liked to get an array of object
with each
identifier:
currently it produces:
{"items":["a1","b1","a2","b2"]}
while it'd be more desirable to have
{"items":[{"a":"a1","b":"b1"}, {"a":"a2","b":"b2"}]}
because the reader will test the presence of each the key "a"
and "b" in
each element of "items".
Would it be a complete non-sense to assign an element with
opIndexAssign(), just like I wrote initially ? I know this is
wrong but
the syntax seemed natural and logic.
Reading from std.json is straightforward but writing looks a
bit messy.
It makes sense to do it. But like I said std.json is rubbish.
Just so you can see why I'm saying vibe.d's json implementation
is better[0].
[0]
https://github.com/rejectedsoftware/vibe.d/blob/master/source/vibe/data/json.d#L1670
Also, look at the new std.json candidate:
http://code.dlang.org/packages/std_data_json