Advertisement
Guest User

json examples

a guest
May 7th, 2013
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.26 KB | None | 0 0
  1. import std.stdio;
  2. import std.algorithm;
  3. import std.array;
  4.  
  5. import json;
  6.  
  7. void main(string[] argv) {
  8.     // Create a JSON object.
  9.     auto obj = jsonObj();
  10.  
  11.     // Assign some values to the object.
  12.     obj["foo"] = 3;
  13.     obj["bar"] = null;
  14.     obj["baz"] = "some string";
  15.     obj["sub"] = jsonObj();
  16.  
  17.     // Iterate over the object.
  18.     foreach(string key, value; obj) {
  19.         writefln("%s : %s", key, value);
  20.     }
  21.  
  22.     // Use 'in' to check existence.
  23.     assert("sub" in obj);
  24.     // cast a number back from the JSON object again.
  25.     assert(cast(int) obj["foo"] == 3);
  26.     // == is overloaded too.
  27.     assert(obj["baz"] == "some string");
  28.     // We have length
  29.     assert(obj.length == 4);
  30.     // This is cast(bool), and it's true because .length > 0
  31.     assert(obj);
  32.  
  33.     // A new array. (JSON)
  34.     auto arr = jsonArr();
  35.  
  36.     // Add on some values.
  37.     arr ~= 3;
  38.     arr ~= 4;
  39.     arr ~= 7;
  40.  
  41.     assert(arr.length == 3);
  42.  
  43.     // .arr gets us a reference to the JSON[], which lets us have some fun.
  44.     assert(arr.arr.map!(j => cast(int) j).array == [3, 4, 7]);
  45.  
  46.     // We can write to the length.
  47.     arr.length = 2;
  48.  
  49.     // Iterate over the array.
  50.     foreach(size_t i, value; arr) {
  51.         writefln("%s : %s", i, value);
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement