Any (working) JSON library for D2?

Johannes Pfau spam at example.com
Sun Jun 19 10:58:57 PDT 2011


Adam D. Ruppe wrote:
>I use std.json with a couple helper function to make it shorter.
>
>To use:
>
>writeln(toJson(whatever));
>
>or
>
>JSONValue val = toJsonValue(whatever);
>
>Works on most basic data types: int, string, array, assoc, struct,
>etc.
>
>=====
>
>import std.json;
>import std.traits;
>import std.conv;
>
>string toJson(T)(T a) {
>	auto v = toJsonValue(a);
>	return toJSON(&v);
>}
>
>JSONValue toJsonValue(T)(T a) {
>	JSONValue val;
>	static if(is(T == JSONValue)) {
>		val = a;
>	} else static if(__traits(compiles, val = a.makeJsonValue())) {
>		val = a.makeJsonValue();
>	} else static if(isIntegral!(T)) {
>		val.type = JSON_TYPE.INTEGER;
>		val.integer = to!long(a);
>	} else static if(isFloatingPoint!(T)) {
>		val.type = JSON_TYPE.FLOAT;
>		val.floating = to!real(a);
>		static assert(0);
>	} else static if(is(T == void*)) {
>		val.type = JSON_TYPE.NULL;
>	} else static if(is(T == bool)) {
>		if(a == true)
>			val.type = JSON_TYPE.TRUE;
>		if(a == false)
>			val.type = JSON_TYPE.FALSE;
>	} else static if(isSomeString!(T)) {
>		val.type = JSON_TYPE.STRING;
>		val.str = to!string(a);
>	} else static if(isAssociativeArray!(T)) {
>		val.type = JSON_TYPE.OBJECT;
>		foreach(k, v; a) {
>			val.object[to!string(k)] = toJsonValue(v);
>		}
>	} else static if(isArray!(T)) {
>		val.type = JSON_TYPE.ARRAY;
>		val.array.length = a.length;
>		foreach(i, v; a) {
>			val.array[i] = toJsonValue(v);
>		}
>	} else static if(is(T == struct)) {
>		val.type = JSON_TYPE.OBJECT;
>
>		foreach(i, member; a.tupleof) {
>			string name = a.tupleof[i].stringof[2..$];
>			static if(a.tupleof[i].stringof[2] != '_')
>				val.object[name] = toJsonValue(member);
>		}
>	} else { /* our catch all is to just do strings */
>		val.type = JSON_TYPE.STRING;
>		val.str = to!string(a);
>	}
>
>	return val;
>}
>
>====

I guess you do not have similar helper functions to parse JSON?
Also how do you workaround bug #2962? Maybe it doesn't occur as long
as only formatting functionality is used, but any call to parseJSON
triggers #2962. The bug is caused by
std.conv.parse!real(string) but I'm not sure how that could be worked
around. Maybe I'll have to remove floating point support and write some
wrappers as you suggested, that could work.

-- 
Johannes Pfau



More information about the Digitalmars-d-learn mailing list