Strange behavior of cast(int[]) json["my int list"].array

Basile B. b2.temp at gmx.com
Wed Nov 15 20:08:37 UTC 2017


On Wednesday, 15 November 2017 at 19:54:20 UTC, Enjoys Math wrote:
> I had it working in an earlier program.
>
> Now I have:
>
>
> main.d
> ------
>
> import std.json;
> import std.file;
>
> int main() {
>    JSONValue settings;
>
>    settings = parseJSON("settings.txt");
>    auto intList = cast(int[]) settings["int list"].array;
>
>    writeln(intList);
>
>    readln();
> }
>
>
> for input:
>
> settings.txt
> ------------
> {
>    "int list" : [1,2,3,4,5]
> }
>
>
> printing:
>
> [1,0,2,0,2,0,2,0,3,0,2, ...] (length = 20)
>
>
> Should I access each member int the array individually?

Hi, your cast is invalid because each element of "array" is 
itself a JSONValue.
You're even lucky to have something that resembles to the input ;)

Try rather:

---
import std.json, std.stdio, std.algorithm, std.array;

void main() {
    JSONValue settings;
    settings = parseJSON(`{"int list" : [1,2,3,4,5]}`);
    // take the int value of each individal element to make the 
array.
    auto intList = settings["int list"].array.map!(a => 
a.integer).array;
    writeln(intList);
}
---


More information about the Digitalmars-d-learn mailing list