On 03/25/2012 08:26 AM, AaronP wrote:
Could I get a "hello, world" example of parsing json? The docs look simple enough, but I could still use an example.
For what it's worth, I've just sent the following program to a friend before seeing this thread.
1) Save this sample text to a file named "json_file" { "employees": [ { "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstName":"Peter" , "lastName":"Jones" } ] } 2) The following program makes struct Employee objects from that file: import std.stdio; import std.json; import std.conv; import std.file; struct Employee { string firstName; string lastName; } void main() { // Assumes UTF-8 file auto content = to!string(read("json_file")); JSONValue[string] document = parseJSON(content).object; JSONValue[] employees = document["employees"].array; foreach (employeeJson; employees) { JSONValue[string] employee = employeeJson.object; string firstName = employee["firstName"].str; string lastName = employee["lastName"].str; auto e = Employee(firstName, lastName); writeln("Constructed: ", e); } } The output of the program: Constructed: Employee("John", "Doe") Constructed: Employee("Anna", "Smith") Constructed: Employee("Peter", "Jones") Ali