- D Cookbook
- Adam D. Ruppe
- 517字
- 2021-07-16 11:50:47
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.
- Create the new object.
- Append the new object to the list.
- Print out the JSON representation.
The code is as follows:
void main() { import std.json, std.algorithm, std.stdio; auto list = parseJSON(`[{"name":"Alice","id":1},{"name":"Bob","id":2}]); foreach(person; list.array.map!(a => a.object)) { writeln("ID #", person["id"].integer, " is ", person["name"].str); } JSONValue newPerson; JSONValue[string] obj; obj["name"].str = "Charlie"; obj["id"].integer = 3; newPerson.object = obj; list.array = list.array ~ newPerson;; // append it to the list writeln(toJSON(&list)); // print out the new json }
It will print the following output:
[{"name":"Alice","id":1},{"name":"Bob","id":2},{"name":"Charlie","id":3}]
How it works…
Phobos' std.json
module provides a tagged union to represent a dynamic JSONValue
. To use it, you can explicitly check the type with the type
property, or simply access the type you need through its str
, object
, array
, integer
, and other properties. It will throw an exception if you try to access a property of the wrong type. You can query the current type with the type
property.
Array elements in std.json
are also JSONValues
, which means they need to be accessed through the type
properties. That is why we called map
on the array. We can't work directly with JSONValue
, so mapping it to an object gives something we can immediately use. The map
function is a function from std.algorithm
that calls the given predicate on each element in the array.
JSONValue
properties are either read or write. We cannot modify them in-place. Instead, we read the data or create a temporary file to do our edits then set the finished data back to it.
Finally, toJSON
takes a pointer to a root element and returns the JSON string it represents.
See also
- http://dlang.org/phobos/std_json.html is the documentation of the
std.json
module. - http://dlang.org/phobos/std_variant.html is the documentation of Phobos' other dynamic type:
Variant
. UnlikeJSONValue
,Variant
can store any type, but it does not do serialization to and from string. - http://wiki.dlang.org/Jsvar describes a module that provides a
var
struct with convenient syntax and a similar type model to JavaScript. We'll also learn some of the techniques that are used in that module later in this book.
- 大學計算機基礎(第三版)
- 從零開始:數字圖像處理的編程基礎與應用
- Apache ZooKeeper Essentials
- Learning Cython Programming(Second Edition)
- Cocos2D-X權威指南(第2版)
- Building a Game with Unity and Blender
- PostgreSQL技術內幕:事務處理深度探索
- MATLAB 2020 從入門到精通
- Python數據分析從0到1
- QGIS By Example
- Windows內核編程
- Learning Material Design
- Python數據可視化之美:專業圖表繪制指南(全彩)
- INSTANT PLC Programming with RSLogix 5000
- 開源網絡地圖可視化:基于Leaflet的在線地圖開發