std.json

Alexsej lexa-skripa at rambler
Wed Jul 4 08:25:54 PDT 2012


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

Your example only works if the json file in UTF-8 (BOM), how to 
make sure that it worked with the files in UTF-8 without BOM.


More information about the Digitalmars-d-learn mailing list