如何将关联数组转换为key:value? [英] How to convert associative array to key:value?
问题描述
我需要转换关联数组,以将其放入Json,但我不能理解如何做到这一点.方法to!string
添加不必要的斜杠.
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]"}
我需要获取:{"tags":{"Python":1}}
我也在考虑使用tuples
,所以如果有什么解决方案,我想看看.
Also I am thinking about using tuples
so if there is any solution for them I would like to look at it.
推荐答案
to!string
是错误的方法.您不想转换为通用字符串,而是转换为JSON.
to!string
is the wrong approach. You don't want to convert to a generic string, but to JSON.
我的第一个想法是tags["tags"] = name;
.但是vibe.d的JSON
似乎没有一个带有通用关联数组的opAssign
.
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.
第二个想法,遍历name
并将其项分配给tags["name"]
:
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);
}
这篇关于如何将关联数组转换为key:value?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!