Converting JSONValue to AssociativeArray.
Steven Schveighoffer
schveiguy at gmail.com
Mon Aug 1 22:47:03 UTC 2022
On 8/1/22 2:00 PM, hype_editor wrote:
> I need to convert variable of type `JSONValue` to variable of type
> `string[string]` (AssociativeArray).
>
> ```d
> import std.json : JSONValue;
> import std.stdio : writefln;
>
> void main()
> {
> JSONValue data = parseJSON(`{ "name": "Hype Editor", "hobby":
> "Programming" }`);
> writefln("%s", data);
>
> auto aa_data = /+ Converting +/;
> writefln("%s", aa_data);
> }
> ```
> And output will be:
> ```bash
> ["name":"Hype Editor","hobby":"Programming"]
> ```
>
> **How can I do this in D?**
>
```d
// option 1
string[string] aa_data;
foreach(string k, v; data) {
aa_data[k] = v.get!string;
}
// option 2
import std.algorithm : map;
import std.array : assocArray;
import std.typecons : tuple;
auto aa_data = data.object
.byKeyValue
.map!(kv => tuple(kv.key, kv.value.get!string))
.assocArray;
```
I personally prefer the straightforward loop.
-Steve
More information about the Digitalmars-d-learn
mailing list