Bug 15410 – std.json documentation implies you *must* assign an AA literal to create an object
Status
RESOLVED
Resolution
INVALID
Severity
enhancement
Priority
P1
Component
phobos
Product
D
Version
D2
Platform
x86_64
OS
Linux
Creation time
2015-12-05T19:00:31Z
Last change time
2020-03-21T03:56:42Z
Assigned to
No Owner
Creator
Neia Neutuladh
Comments
Comment #0 by dhasenan — 2015-12-05T19:00:31Z
opIndex(string) says:
"Throws JSONException if type is not JSON_TYPE.OBJECT."
This implies the correct way to create a JSONValue of type OBJECT, assuming you don't want to use an AA literal, is:
---
JSONValue j;
j.type = JSON_TYPE.OBJECT;
j["key"] = "value";
---
However, when you try that, the compiler warns:
Deprecation: function std.json.JSONValue.type is deprecated - Please assign the value with the adequate type to JSONValue directly.
In my use case, it would be unnatural and troublesome to assign an AA literal directly. So now I'm looking for a magic incantation that will maybe work. I could try something like:
---
JSONValue j = ["": ""];
j.remove("");;
---
Except JSONValue, as far as the documentation states, is append-only. (Is it really? Who knows?)
That leaves only one method to create an empty JSON object:
---
JSONValue j = "{}".parseJSON;
---
That's terrible.
However! The documentation is actually wrong! I can just write:
---
JSONValue j;
j["key"] = "value";
---
That works! The documentation told me it would throw an exception, so there was no reason for me to try it. It was guaranteed to me that it would fail. But instead it succeeded.
This is making me bitter and jaded.
Comment #1 by b2.temp — 2015-12-05T19:26:39Z
(In reply to Chris Wright from comment #0)
> opIndex(string) says:
>
> "Throws JSONException if type is not JSON_TYPE.OBJECT."
>
> This implies the correct way to create a JSONValue of type OBJECT, assuming
> you don't want to use an AA literal, is:
>
> [...]
>
> However! The documentation is actually wrong! I can just write:
>
> ---
> JSONValue j;
> j["key"] = "value";
> ---
>
> That works! The documentation told me it would throw an exception, so there
> was no reason for me to try it. It was guaranteed to me that it would fail.
> But instead it succeeded.
Your report is invalid.
You say that 'opIndex(string)' ddoc specifies that it throws. But what you call is not opIndex(), it's opIndexAssign()!!!
And 'opIndexAssign' ddoc says:
/// Operator sets value for element of JSON object by key.
/// If JSON value is null, then operator initializes it with object and then
/// sets value for it.
/// Throws JSONException if type is not JSON_TYPE.OBJECT or JSON_TYPE.NULL
Your 'j' is initially null, then the call to opIndexASsign initializes j as a JSONObject.