A trick to control the key ordering of JSONValue.toString

timepp tongjunhui at live.cn
Fri Jan 4 07:38:39 UTC 2019


As documented, when you output a JSONValue to string, keys are 
always in ascent order. In some case the output will be consumed 
by human so a specific key order is important.

This really caused my headache for some time. When I was about to 
rewrite my own toString method I found a quick, dirty but clever 
idea as below.

string toPrettyStringWithOrder(JSONValue j, string[] keys) {
	auto str = j.toString();
	for (int i = 0; i < keys.length; i++) {
		string oldkey = keys[i];
		string newkey = format("__%02d__", i) ~ oldkey;
		str = str.replace("\"" ~ oldkey ~ "\":", "\"" ~ newkey ~ "\":");
	}
	JSONValue jj = parseJSON(str);
	str = jj.toPrettyString();
	
	auto re = regex(r"__[0-9][0-9]__","g");
	return replaceAll(str, re, "");
}

my usage:
f.write(toPrettyStringWithOrder(j, ["name", "group", "type", 
"talent", "skill", "source", "tag", "gallary"]));

It lacks of preciseness. But it's enough to me. Hope this help 
you as well.


More information about the Digitalmars-d mailing list