Any (working) JSON library for D2?

Johannes Pfau spam at example.com
Sun Jun 19 11:01:39 PDT 2011


Adam D. Ruppe wrote:
>Oh, wait a minute, you were doing from json, not to json.
>
>Try this on for size. It converts from a std.json.JSONValue
>to a std.variant.Varaint, which is quite a bit simpler to use.
>
>======
>
>import std.variant;
>import std.json;
>
>Variant jsonToVariant(string json) {
>	auto decoded = parseJSON(json);
>	return jsonValueToVariant(decoded);
>}
>
>Variant jsonValueToVariant(JSONValue v) {
>	Variant ret;
>
>	final switch(v.type) {
>		case JSON_TYPE.STRING:
>			ret = v.str;
>		break;
>		case JSON_TYPE.INTEGER:
>			ret = v.integer;
>		break;
>		case JSON_TYPE.FLOAT:
>			ret = v.floating;
>		break;
>		case JSON_TYPE.OBJECT:
>			Variant[string] obj;
>			foreach(k, val; v.object) {
>				obj[k] = jsonValueToVariant(val);
>			}
>
>			ret = obj;
>		break;
>		case JSON_TYPE.ARRAY:
>			Variant[] arr;
>			foreach(i; v.array) {
>				arr ~= jsonValueToVariant(i);
>			}
>
>			ret = arr;
>		break;
>		case JSON_TYPE.TRUE:
>			ret = true;
>		break;
>		case JSON_TYPE.FALSE:
>			ret = false;
>		break;
>		case JSON_TYPE.NULL:
>			ret = null;
>		break;
>	}
>
>	return ret;
>}
>
>======

Thanks, that looks great!
Can't test it right now, but it seems this even works recursively?
Awesome!

-- 
Johannes Pfau



More information about the Digitalmars-d-learn mailing list