question

Choi Hyun Woong avatar image
0 Likes"
Choi Hyun Woong asked Jason Lightfoot commented

How do I convert a json type message to a string?

As always, thank you for your help.


How do I convert a json type message to a string?

For example, if you try to convert the following json message to a string:

{"type":"A","pose":{"x":0,"y":0,"theta":0}}


string str = "{"type":"A","pose":{"x":0,"y":0,"theta":0}}";


The following error occurs:


Flexscript Error VIEW:/active/MainPanel/BackPanel/SplitterXPane/SplitterYPane/SplitterXPane~2/ToolTabPane/TabControl/ScriptConsole/Script>script Line 1 syntax error

Could not finish parsing because of previous errors.


What's the problem?

FlexSim 24.1.0
json data
5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.

1 Answer

Joerg Vogel avatar image
1 Like"
Joerg Vogel answered Jason Lightfoot commented

If you would use a map by keywords type and pose, then you could build a string by stringify method, won’t you?

Edit: The problem is, that you need to parse a double quotation mark by an escape sequence into a string. Otherwise you would close a string.

\' Inserts a single quotation mark in the string.
· 4
5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.

Jason Lightfoot avatar image Jason Lightfoot ♦♦ commented ·

So:

string s="{\"type\":\"A\",\"pose\":{\"x\":0,\"y\":0,\"theta\":0}}";
return JSON.parse(s);

returns:

Map:    {type: A, pose: {x: 0, y: 0, theta: 0}}


Of course if you're receiving a message from elsewhere then you don't need to convert anything or use escape characters - it's just when you're constructing it in FlexSim using this technique.

As Jörg points out you can use a map and then stringify it for your test:

Map m;
m.type="A";
Map p;
p.x=0;
p.y=0;
p.theta=0;
m.pose=p;
return JSON.stringify(m);


2 Likes 2 ·
Choi Hyun Woong avatar image Choi Hyun Woong Jason Lightfoot ♦♦ commented ·

Thank you for your kindly reply!

0 Likes 0 ·
Choi Hyun Woong avatar image Choi Hyun Woong commented ·

Thank you for reply!

Are JSON messages received through MQTT broker stored as strings in emulation variables(Emulation().variables) without double quotation? Or is double quotation applied internally and stored as a string?

0 Likes 0 ·
Jason Lightfoot avatar image Jason Lightfoot ♦♦ Choi Hyun Woong commented ·

Messages should have double quotation marks in the string - the need for escape characters is just to tell the FlexScript interpreter which quotes are included in the string and which denote the start/end of the string.

1 Like 1 ·