RejectedSoftware Forums

Sign up

Construct complex Json with inner members with member access?

I would like to get something like:

{"collection":"tags","example":{"name":"dima"}}

I am doing:

	Json x = Json.emptyObject;
	x.collection = "tags";
	x.example = `{"name":"dima"}`;
	writeln(x.toString);

I am getting:

{"collection":"tags","example":"{\"name\":\"dima\"}"}

What I am doing wrong? How to prevent slashes appearing?

Re: Construct complex Json with inner members with member access?

On Mon, 07 Sep 2015 20:50:31 GMT, Suliman wrote:

I would like to get something like:

{"collection":"tags","example":{"name":"dima"}}

I am doing:

	Json x = Json.emptyObject;
	x.collection = "tags";
	x.example = `{"name":"dima"}`;
	writeln(x.toString);

I am getting:

{"collection":"tags","example":"{\"name\":\"dima\"}"}

What I am doing wrong? How to prevent slashes appearing?

Yes, you're assigning a string to a Json object's member.
You need to create a new object first, and then assign members to it.

auto x = Json.emptyObject;
x.collection = "tags";
x.example = Json.emptyObject;
x.example.name = "dima";
writeln(x.toString);

Also, I believe the x.prop syntax is going to be deprecated, so you should instead use:

auto x = Json.emptyObject;
x["collection"] = "tags";

auto example = Json.emptyObject;
example["name"] = "dima";

x["example"] = example;

Re: Construct complex Json with inner members with member access?

How to change output order?

Json statusJSON = Json.emptyObject;
Json answerJSON = Json.emptyObject; 

tatusJSON["status"] = "fail"; // user exists in DB, password NO
answerJSON["password"] = "wrongPassword"; // user exists in DB, password NO
answerJSON["isAuthorized"] = false;
statusJSON["error"] = answerJSON;
logInfo("-------------------------------------------------------------------------------");
logInfo(statusJSON.toString);
readln;
logInfo("^-----------------------------------------------------------------------------^");                              
logWarn("WRONG password for USER: %s", request["username"]); //getting username from request

{"error":{"isAuthorized":false,"password":"wrongPassword"},"status":"fail"}

I would like to do:
"status":"fail", {"error":{"isAuthorized":false,"password":"wrongPassword"}}

Re: Construct complex Json with inner members with member access?

On Thu, 14 Jan 2016 08:17:20 GMT, Suliman wrote:

{"error":{"isAuthorized":false,"password":"wrongPassword"},"status":"fail"}

I would like to do:
"status":"fail", {"error":{"isAuthorized":false,"password":"wrongPassword"}}

You can use a struct and serializeToJsonString (or pass the struct to res.writeJsonBody):

struct PasswordError {
  bool isAuthorized;
  string password;
}
struct ErrorStatus {
  string status;
  PasswordError error;
}

logInfo(%s, ErrorStatus("fail", PasswordError(false, "wrongPassword")).serializeToJsonString());