On Mon, 13 Sep 2010 18:59:57 -0400, sybrandy <[email protected]> wrote:
On 09/12/2010 10:53 PM, Brian Schott wrote:
Everything is a JSONValue. JSONValue has a union inside it that actually
holds the data. I just wrote a short program that reads your example
file. (This could be a bit more efficient if I stored obj2, but I think
it's enough to communicate the idea.)
import std.stdio;
import std.json;
import std.file;
void main(string[] args)
{
auto jsonString = readText("../ml.json");
JSONValue json = parseJSON(jsonString);
writeln(json["obj1"]["obj2"]["val1"].integer);
writeln(json["obj1"]["obj2"]["val2"].str);
foreach(value; json["obj1"]["val3"].array)
writeln(value.integer);
}
Output:
1
a string
1
2
3
4
Your question did remind me to document the union members so that the
HTML documentation will show how to access the actual data. I've
uploaded the new version of the file. The link is the same.
Cool. It looks very simple and easy...just the way I like it. What you
have is actually quite nice as I can navigate down to a low-level
element without having to store 200 different intermediate values.
Probably not very common, but a nicety for when it's needed.
Thanks!
Casey
Unfortunately, the above code is horribly broken. Here's how to read a
number correctly:
real x;
if(json["vector"]["x"].type == JSON_TYPE.INTEGER) {
x = json["vector"]["x"].integer;
} else if(json["vector"]["x"].type == JSON_TYPE.FLOAT) {
x = json["vector"]["x"].floating;
} else {
enforceEx!(JSONException)(false);
}
You'll notice that before any access you must check to ensure the JSON
type is what you think it should be. As noted above, JSON does not
differentiate between integers and reals, so you have to test both on
access.