Json in Chapel

Our first program will demonstrate JSON encoding and decoding in Chapel. Here’s the full source code:

use JSON;

// Define custom record types for JSON serialization
record Response1 {
  var page: int;
  var fruits: [1..0] string;
}

record Response2 {
  var page: int;
  var fruits: [1..0] string;
}

proc main() {
  // Encoding basic data types to JSON strings
  writeln(jsonEncode(true));
  writeln(jsonEncode(1));
  writeln(jsonEncode(2.34));
  writeln(jsonEncode("gopher"));

  // Encoding arrays and associative arrays
  var slcD = ["apple", "peach", "pear"];
  writeln(jsonEncode(slcD));

  var mapD = ["apple" => 5, "lettuce" => 7];
  writeln(jsonEncode(mapD));

  // Encoding custom record types
  var res1D = new Response1(1, ["apple", "peach", "pear"]);
  writeln(jsonEncode(res1D));

  var res2D = new Response2(1, ["apple", "peach", "pear"]);
  writeln(jsonEncode(res2D));

  // Decoding JSON data into Chapel values
  var jsonStr = '{"num":6.13,"strs":["a","b"]}';
  var dat = jsonDecode(jsonStr);
  writeln(dat);

  var num = dat["num"]:real;
  writeln(num);

  var strs = dat["strs"]:list(string);
  var str1 = strs[0];
  writeln(str1);

  // Decoding JSON into custom record types
  var jsonStr2 = '{"page": 1, "fruits": ["apple", "peach"]}';
  var res = jsonDecode(jsonStr2, Response2);
  writeln(res);
  writeln(res.fruits[0]);

  // Writing JSON directly to stdout
  var d = ["apple" => 5, "lettuce" => 7];
  stdout.write(jsonEncode(d));
}

This Chapel program demonstrates JSON encoding and decoding using the JSON module. Here’s a breakdown of what the code does:

  1. We define custom record types Response1 and Response2 for JSON serialization.

  2. In the main procedure, we start by encoding basic data types to JSON strings using jsonEncode().

  3. We then encode arrays and associative arrays (Chapel’s equivalent to Go’s maps).

  4. Custom record types are encoded to JSON.

  5. We demonstrate decoding JSON data into Chapel values using jsonDecode(). The decoded data is stored in a variable of type owned JsonNode.

  6. We access and print values from the decoded JSON data.

  7. We show how to decode JSON into custom record types.

  8. Finally, we demonstrate writing JSON directly to stdout.

To run the program, save it as json_example.chpl and use the Chapel compiler:

$ chpl json_example.chpl -o json_example
$ ./json_example

This will compile and run the program, displaying the JSON encoding and decoding results.

Note that Chapel’s JSON handling might differ slightly from Go’s in terms of syntax and available methods, but the overall concepts of encoding and decoding JSON data are similar.