How to convert associative array to key:value?

自闭症网瘾萝莉.ら 提交于 2019-12-11 10:55:39

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!