Casting JSONValues arrays to native arrays ... ??? ...
Steven Schveighoffer
schveiguy at gmail.com
Fri Sep 24 12:25:48 UTC 2021
On 9/24/21 12:58 AM, james.p.leblanc wrote:
> On Thursday, 23 September 2021 at 20:32:36 UTC, james.p.leblanc wrote:
>> On Thursday, 23 September 2021 at 19:18:11 UTC, james.p.leblanc wrote:
>>> On Thursday, 23 September 2021 at 19:04:47 UTC, Steven Schveighoffer
>>> wrote:
>>>> On 9/23/21 2:20 PM, james.p.leblanc wrote:
>>
>> ```
>> Produces:
>>
>> typeid(jj): std.json.JSONValue, jj:
>> {"ba":[true,false,true],"d":[1.23399999999999999]}
>> typeid(z5): question.main.MapResult!(__lambda2,
>> JSONValue[]).MapResult, z5: [true, false, true]
>> z5: [true, false, true]
>>
>
> Sigh ... my suggested "minor edit" above produces a "map result" instead of
> the desired native array ... here is the **fix** by appending ".array"
> at the
> end (which is the suffix Steve originally offered). The following gives
> the desired **bool[]** result.
>
> ```d
> import std.array;
>
> auto z5 = jj["ba"].array.map!(v => v.get!bool).array;
> writeln("typeid(z5): ", typeid(z5), ", z5: ", z5);
> writeln("z5: ", z5);
> ```
At first I thought that was allocating 2 arrays, but I didn't realize
`JSONValue.array` was an actual member! When I saw your original code, I
assumed the `.array` call was a call to `std.array.array`, and that
`JSONValue` was somehow usable as a range.
So yes, that's what I should have written.
I admit I have not used `JSONValue`. That `array` accessor is quite a
poor name due to the vast prevalence of using `std.array.array` to make
an array out of some range. When using vibe.d's JSON type, I usually do
`jsval[]` to access the array portion.
Note, you may want to consider whether you actually need a concrete
array, as using the map result is pretty much equivalent, yet doesn't
allocate anything.
-STeve
More information about the Digitalmars-d-learn
mailing list