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.

Reply via email to