问题
I need to convert associative array, to put them to Json, but I can't understanf how to do it. Method to!string
add unnecessary slashes.
int[string] name;
name["Python"] = 5;
Json tags = Json.emptyObject; //Json object
tags["tags"] = name.to!string;
writeln(tags);
{"tags":"[\"Python\":1]"}
I need to get: {"tags":{"Python":1}}
Also I am thinking about using tuples
so if there is any solution for them I would like to look at it.
回答1:
to!string
is the wrong approach. You don't want to convert to a generic string, but to JSON.
My first idea would be tags["tags"] = name;
. But vibe.d's JSON
doesn't seem to have an opAssign
that takes a generic associative array.
Second idea, loop over name
and assign its items to tags["name"]
:
import vibe.data.json;
import std.stdio;
void main()
{
int[string] name;
name["Python"] = 5;
Json tags = Json.emptyObject; //Json object
tags["tags"] = Json.emptyObject;
foreach (k, v; name) tags["tags"][k] = v;
writeln(tags);
}
来源:https://stackoverflow.com/questions/32680906/how-to-convert-associative-array-to-keyvalue