Example of parse whole json answer.
Craig Dillabaugh via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Apr 24 05:47:40 PDT 2014
On Thursday, 24 April 2014 at 12:17:42 UTC, Nicolas wrote:
> I have a json string saved in a file ( example of json tweeter
> answer:
> https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
> ). I am trying to read the whole json answer and print specific
> data ("created_at", "retweet_count", ..) . I am new at D
> Programming language and i was wondering if someone can help me
> or post some example that show how to parse json strings using
> std.json library. Thanks in advance.
Here is something to get you started. The initial version of
this code was from Ali Cehreli, I can't remember what
modifications are mine, or if this is all straight form Ali.
If you intend to do any serious work with Json, I highly
recommend you check out Vibe.d (www.vibed.org) - more stuff to
learn but its JSON capabilities are awesome compared to what
std.json gives you.
import std.stdio;
import std.json;
import std.conv;
import std.file;
/**
Ali's example.
*/
struct Employee
{
string firstName;
string lastName;
}
void readEmployees( string employee_json_string )
{
JSONValue[string] document =
parseJSON(employee_json_string).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);
}
}
void main()
{
// Assumes UTF-8 file
auto content =
`{
"employees": [
{ "firstName":"Walter" , "lastName":"Bright" },
{ "firstName":"Andrei" , "lastName":"Alexandrescu" },
{ "firstName":"Celine" , "lastName":"Dion" }
]
}`;
readEmployees( content );
//Or to read the same thing from a file
readEmployees( readText( "employees.json" ) );
}
More information about the Digitalmars-d-learn
mailing list