JSON to Pike classes
Pike is a dynamic language with a C-like syntax and optional static types, used in projects such as the Roxen web server. Its standard library decodes JSON with Standards.JSON.decode into mappings and arrays. This JSON to Pike generator turns a sample into typed classes and conversion functions, so the rest of your program can work with named members instead of mapping lookups.
Example
{ "id": 42, "title": "Write docs", "done": false,
"owner": { "name": "Ada", "email": null },
"subtasks": [ { "title": "Outline", "estimate": 2 }, { "title": "Draft" } ] }
class Task {
int id; // json: "id"
string title; // json: "title"
bool done; // json: "done"
Owner owner; // json: "owner"
array(Subtask) subtasks; // json: "subtasks"
string encode_json() {
mapping(string:mixed) json = ([
"id" : id,
"title" : title,
// ...
]);
return Standards.JSON.encode(json);
}
}
Task Task_from_JSON(mixed json) {
Task retval = Task();
retval.id = json["id"];
// ...
return retval;
}
Each member is annotated with a comment naming its JSON key, arrays use Pike's typed array(T) syntax, and values of uncertain type are declared mixed.
How types are inferred
Whole numbers become int, decimals float, strings string and booleans bool. Arrays use Pike's typed array(T), and nested objects become their own classes. When values of different types appear together, the generator declares a type alias such as typedef int|string X;, using Pike's union types. Dates remain strings, since JSON has no date type.
Using the generated code
mixed data = Standards.JSON.decode(json_string);
Task task = Task_from_JSON(data);
write("%s\n", task.title);
string out = task->encode_json();
Import the file as a Pike module and call the _from_JSON function for the top-level class. To encode, call encode_json() on the object, or pass the object to Standards.JSON.encode.
Caveats
As the generated header comment warns, the decoding functions assume the JSON matches the sample: they assign values directly, so an unexpected shape can raise an error or produce members with the wrong type even though the JSON itself is valid. Check critical input before decoding, for example by testing mappingp(data) and the presence of required keys. Nested objects are also assigned as decoded mappings unless you pass them through their own _from_JSON function, so review nested members after generating.
Validate your sample with the JSON Validator, and format it with the JSON Formatter first if it is minified. Generation runs in your browser.