Writing a JSON object or string in a C2 text field

For developers using the Construct 2 Javascript SDK

Post » Sun Feb 10, 2013 9:08 am

Hello,

I've been amending the socket.io plugin so I can receive JSON and pick a value and also emit it back.

I've been successful implementing a new LastDataAtVar("variable") expression which can pick a variable from incoming JSON object.

e.g. server does:

this.broadcast.emit("new player", {id: newPlayer.id, x: newPlayer.getX(), y: newPlayer.getY()});

I can handpick the values.

However, now I'd like do something like:

Socket On Event "move player" : Emit '{"x":"' & MyPlayer.x & '","y":"' & MyPlayer.y & '"}'

The problem is Construct 2 does not allow me to write strings in this way because of the error checking...although it is a string.

If I could do this, I could then just JSON.parse() it. Even better would be to write JSON directly into the field without it being a string.

Any ideas on getting around this?

Cheers
B
5
Posts: 39
Reputation: 678

Post » Sun Feb 10, 2013 10:22 am

@aceofpack

You only could use string then transfer to JSON object since the parameter of expression only accepts string or number type.
Or add some actions to create JSON object by "key:value" pair.rexrainbow2013-02-10 10:23:50
B
97
S
22
G
177
Posts: 4,111
Reputation: 103,525

Post » Sun Feb 10, 2013 11:49 am

@rexrainbow

Thanks for your response.

The problem is that the string: '{"x":"' & MyPlayer.x & '","y":"' & MyPlayer.y & '"}'

..is not seen as a string - CS2 doesn't like strings started with ' or using an escape character \.

I guess i'll have to try and implement the later method you describe.

Cheers

B
5
Posts: 39
Reputation: 678

Post » Sun Feb 10, 2013 11:57 am

Can you not just escape the double quotes in the string?
Moderator
B
72
S
13
G
11
Posts: 900
Reputation: 11,783

Post » Sun Feb 10, 2013 12:00 pm

No, it doesn't like the \ either.
B
5
Posts: 39
Reputation: 678

Post » Sun Feb 10, 2013 12:04 pm

"{\"y\":\"" & int(MyPlayer.Y) & "\"}" <- gives me syntax error unknown character (pointing to the \).

B
5
Posts: 39
Reputation: 678

Post » Sun Feb 10, 2013 12:18 pm

Try Double "" in string to replace single "
B
97
S
22
G
177
Posts: 4,111
Reputation: 103,525

Post » Sun Feb 10, 2013 12:59 pm

Great :)

That works:

"{""y"":""" & int(MyPlayer.Y) & """}"

A bit of an eyesore but it works!
B
5
Posts: 39
Reputation: 678


Return to Javascript SDK

Who is online

Users browsing this forum: No registered users and 2 guests