RejectedSoftware Forums

Sign up

Json array repetition

I am trying to append an array to a Json variable but it ends up repeating the last element over the entire array. For example, if my array should be {"prop":"test1"},{"prop":"test 2"},{"prop":"test3"}, it comes out as {"prop":"test3"},{"prop":"test3"},{"prop":"test3"}.

My most recent attempt is:

Json elecArray = Json.emptyObject;
result["elec"] = Json.emptyArray;
	
foreach(ELEC; elecColl.find(["committee":orgID]))
{
     elecArray["prop"] = ELEC["proposal"].toJson;
     elecArray["id"] = ELEC["_id"].toJson;

     if (ELEC["ballotClosed"].get!bool is false)
     {
    	elecArray["res"] = "OPEN";
     } else if (ELEC["numFavor"].get!long > ELEC["numOppose"].get!long) {
    	elecArray["res"] = "PASS";
     } else {
    	elecArray["res"] = "FAIL";
     }
     result["elec"].appendArrayElement(elecArray);
}

Or simplified:

Json elecArray = Json.emptyObject;
result["elec"] = Json.emptyArray;
	
foreach(ELEC; elecColl.find(["committee":orgID]))
{
     elecArray["prop"] = ELEC["proposal"].toJson;
     elecArray["id"] = ELEC["_id"].toJson;


     result["elec"].appendArrayElement(elecArray);
}

Re: Json array repetition

On Tue, 17 May 2016 03:37:20 GMT, Chuck wrote:

I am trying to append an array to a Json variable but it ends up repeating the last element over the entire array. For example, if my array should be {"prop":"test1"},{"prop":"test 2"},{"prop":"test3"}, it comes out as {"prop":"test3"},{"prop":"test3"},{"prop":"test3"}.

...

Json elecArray = Json.emptyObject;
result["elec"] = Json.emptyArray;
	
foreach(ELEC; elecColl.find(["committee":orgID]))
{
      elecArray["prop"] = ELEC["proposal"].toJson;
      elecArray["id"] = ELEC["_id"].toJson;


      result["elec"].appendArrayElement(elecArray);
}

The problem is that the foreach loop just overwrites the same internal associative array entries in each iteration, but every array entry still references the same associative array. Moving the Json elecArray = Json.emptyObject; inside of the loop should fix this.

Re: Json array repetition

The problem is that the foreach loop just overwrites the same internal associative array entries in each iteration, but every array entry still references the same associative array. Moving the Json elecArray = Json.emptyObject; inside of the loop should fix this.

That worked perfectly. Many thanks!