std.json

Craig Dillabaugh cdillaba at cg.scs.carleton.ca
Wed Nov 20 05:16:58 PST 2013


On Monday, 26 March 2012 at 07:14:50 UTC, Ali Çehreli wrote:
> 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

So I was thinking of adding an example to the std.json documents,
and was going to ask to rip-off Ali's example here.  However, I
thought I would be nice to have an example going the other way
(ie. taking some data structure and converting to JSON format).
I came up with the following using Ali's Employee struct:

/**
   * Generate a JSON string from an array of employees using
std.json,
   * even though the code to generate the same by hand would be
shorter
   * and easier to follow :o)
   */
string employeesToJSON( Employee[] employees )
{
      JSONValue emp_array;
      emp_array.type = JSON_TYPE.ARRAY;
      emp_array.array = [];

      foreach( e; employees ) {
	JSONValue emp_object;
	emp_object.type = JSON_TYPE.OBJECT;
	emp_object.object = null;
	
	JSONValue first_name;
	first_name.str = e.firstName;
	first_name.type = JSON_TYPE.STRING;
	
	JSONValue last_name;
	last_name.str = e.lastName;
	last_name.type = JSON_TYPE.STRING;
	
	emp_object.object["firstName"] = first_name;
	emp_object.object["lastName"] = last_name;
	
	emp_array.array ~= emp_object;
      }

      JSONValue root;
      root.type = JSON_TYPE.OBJECT;
      root.object[""] = emp_array;

      return toJSON( &root );
}

Then if I call it using the following code:

	Employee[] employees =  [ { "Walter", "Bright" },
				  { "Andrei", "Alexandrescu"},
				  { "Celine", "Dion" } ];
	
	writeln( employeesToJSON( employees ) );

It prints out:

{"":[{"lastName":"Bright","firstName":"Walter"},{"lastName":"Alexandrescu","firstName":"Andrei"},{"lastName":"Dion","firstName":"Celine"}]}

Which isn't exactly what I want as I have the extra "" at the
start.

So I have two questions:

1. Is there a nicer way to generate my JSONValue tree.

2. How do I insert my JSONValue.array of employees into my root
JSONValue.
I tried:
    root.object[""] = emp_array; // generates { "": [ ... }
    root.object[null] = emp_array; // generates { "": [ ... }
    root.object = emp_array; //Syntax error
      //Error: cannot implicitly convert expression
      //(emp_array) of type JSONValue to JSONValue[string]
I want my returned string as { [ ... ] }

Cheers,

Craig






More information about the Digitalmars-d-learn mailing list