www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Foreach output into a multi dimensional associative array.

reply Vino <akashvino79 gmail.com> writes:
Hi All,

   Request your help on the below on how to store the output to a 
multi dimensional associative array.

Code:

import std.stdio: writeln;
import asdf: parseJson;
import std.conv: to;

void main()
{
  string[int][string] aa;
  string apidata = `{"items":
   [
     {"name":"T01","hostname":"test01","pool":"Development"}
     {"name":"T02","hostname":"test02","pool":"Quality"},
     {"name":"T03","hostname":"test03","pool":"Production"}
   ]
   }`;
  auto jv = parseJson(apidata);
   foreach(j; jv["items"].byElement()){
       aa["Name"] = j["name"].get!string("default");
        i++;
   }
   writeln(aa);
}

Expected Output
aa["Name"] = [T01, T01, T03]
aa["Hostname"] = [test01, test02, test03]
aa["Pool"] = [Development, Quality, Production]

From,
Vino.B
Oct 26 2020
parent reply Imperatorn <johan_forsberg_86 hotmail.com> writes:
On Monday, 26 October 2020 at 19:05:04 UTC, Vino wrote:
 Hi All,

   Request your help on the below on how to store the output to 
 a multi dimensional associative array.

 Code:

 import std.stdio: writeln;
 import asdf: parseJson;
 import std.conv: to;

 void main()
 {
  string[int][string] aa;
  string apidata = `{"items":
   [
     {"name":"T01","hostname":"test01","pool":"Development"}
     {"name":"T02","hostname":"test02","pool":"Quality"},
     {"name":"T03","hostname":"test03","pool":"Production"}
   ]
   }`;
  auto jv = parseJson(apidata);
   foreach(j; jv["items"].byElement()){
       aa["Name"] = j["name"].get!string("default");
        i++;
   }
   writeln(aa);
 }

 Expected Output
 aa["Name"] = [T01, T01, T03]
 aa["Hostname"] = [test01, test02, test03]
 aa["Pool"] = [Development, Quality, Production]

 From,
 Vino.B
Some comments: 1. You're missing a comma (,) after the first item in your apidata 2. You're creating a string[int][string] instead of string[][string] (your expected output) 3. Where is i++ coming from? https://run.dlang.io/is/jfPoeZ
Oct 27 2020
parent Vino <akashvino79 gmail.com> writes:
On Tuesday, 27 October 2020 at 08:00:55 UTC, Imperatorn wrote:
 On Monday, 26 October 2020 at 19:05:04 UTC, Vino wrote:
 [...]
Some comments: 1. You're missing a comma (,) after the first item in your apidata 2. You're creating a string[int][string] instead of string[][string] (your expected output) 3. Where is i++ coming from? https://run.dlang.io/is/jfPoeZ
Hi, Thank yu very much, your suggestion resolved my issue.
Oct 28 2020