Skip to content
penduin edited this page Aug 18, 2012 · 13 revisions

The following JavaScript code...

var doc = {
    "name": "Serenity",
    "class": "firefly",
    "crew": [
        {
            "name": "Malcolm Reynolds",
            "job": "captain",
            "born": 2468
        },
        {
            "name": "Kaywinnet Lee Fry",
            "job": "mechanic",
            "born": 2494
        },
        {
            "name": "Jayne Cobb",
            "job": "public relations"
            "born": 2485
        }
    ]
};
var person = null;

for(i in doc.crew) {  /* note: tedious... */
    person = doc.crew[i];
    if(person.born == 2468) {
        person.born = 2486;
    }
}

for(i in doc.crew) {
    person = doc.crew[i];
    console.log(person.name +" ("+ person.job +") is "+ (2517 - person.born));
}

console.log(JSON.stringify(doc));

...is functionally the same as the following C code using WJElement:

WJElement doc = NULL;
WJElement person = NULL;

doc = WJEObject(NULL, NULL, WJE_NEW);
WJEString(doc, "name", WJE_SET, "Serenity");
WJEString(doc, "class", WJE_SET, "firefly");
WJEArray(doc, "crew", WJE_SET);

WJEObject(doc, "crew[$]", WJE_NEW);
WJEString(doc, "crew[-1].name", WJE_SET, "Malcolm Reynolds");
WJEString(doc, "crew[-1].job", WJE_SET, "captain");
WJEInt64(doc, "crew[-1].born", WJE_SET, 2468);

WJEObject(doc, "crew[$]", WJE_NEW);
WJEString(doc, "crew[-1].name", WJE_SET, "Kaywinnet Lee Fry");
WJEString(doc, "crew[-1].job", WJE_SET, "mechanic");
WJEInt64(doc, "crew[-1].born", WJE_SET, 2494);

WJEObject(doc, "crew[$]", WJE_NEW);
WJEString(doc, "crew[-1].name", WJE_SET, "Jayne Cobb");
WJEString(doc, "crew[-1].job", WJE_SET, "public relations");
WJEInt64(doc, "crew[-1].born", WJE_SET, 2485);

WJEInt64(doc, "crew[].born == 2468", WJE_SET, 2486);  /* note: awesome! */

while((person = _WJEObject(doc, "crew[]", WJE_GET, &person))) {
    printf("%s (%s) is %d\n",
           WJEString(person, "name", WJE_GET, ""),
           WJEString(person, "job", WJE_GET, ""),
           2517 - WJEInt64(person, "born", WJE_GET, 0));
}

WJEDump(doc);
WJECloseDocument(doc);

Notice how similar the code is both in length and clarity. In fact, using WJElement Selectors can make finding and manipulating JSON data even easier and faster in C than in JS!

Clone this wiki locally