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:
Parse the JSON string.
Loop over the array, getting objects out.
Print the information we need, getting the types out of the web API's specification...