Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using the std.json module


JSON is a common data interchange format used on the Web. Phobos has a std.json module that can be used to read and write JSON data. The std.json module is an old module that doesn't take advantage of many of D's advanced features, making it somewhat difficult to use. While newer JSON libraries exist for D, including ones that can be used with syntax and convenience, which is extremely similar to JavaScript itself, Phobos has not yet adopted any of them. Here, we'll read a JSON string, print the current contents, add a new field, and then print out the new JSON.

How to do it…

Suppose we're consuming a web API that returns an array of person objects with a name and ID field. We get the following JSON string from the API:

[{"name":"Alice","id":1},{"name":"Bob","id":2}]

Let's execute the following steps to use the std.json module:

  1. Parse the JSON string.

  2. Loop over the array, getting objects out.

  3. Print the information we need, getting the types out of the web API's specification...