On Friday, 26 August 2016 at 06:56:06 UTC, Alex wrote:
Hi everybody,
I'm little at loss: as documented, a JSONValue is only shallow
copied:
...
So the effect that the code of "j" is altered was expected.
The question is: how to make a deep copy of a JSONValue? Is
there a simple way without copying the source string around?
Or, would this be the simplest way?
Thanks in advance
Alex
Another way is to implement deepCopy by yourself (something like
below)
import std.json;
import std.stdio;
JSONValue deepCopy(ref JSONValue val)
{
JSONValue newVal;
switch(val.type)
{
case JSON_TYPE.STRING:
newVal = JSONValue(val.str.idup);
break;
case JSON_TYPE.OBJECT:
foreach (string key, value; val)
{
newVal[key] = value.deepCopy;
}
break;
case JSON_TYPE.ARRAY:
foreach (size_t index, value; val)
{
newVal[index] = value.deepCopy;
}
break;
default:
newVal = val;
}
return newVal;
}
void main()
{
string s = "{ \"language\": \"D\", \"rating\": 3.14,
\"code\": 42 }";
JSONValue j = parseJSON(s);
writeln("code: ", j["code"].integer);
auto j2 = j.deepCopy;
j2["code"] = 43;
writeln("code of j2: ", j2["code"].integer);
writeln("code of j: ", j["code"].integer);
}