#1 2019-02-04 12:43:25

StxLog
Member
From: France
Registered: 2015-09-14
Posts: 58

Single quote and JSON in MVCApplication

Hi,

In my web application (TMVCApplication), I'd like to send a JSON object to my view, who contains a string with a single quote:

procedure TWebApp.Test(var Scope: Variant);
var
  aSomeText: RawUTF8;
  aVarRes: Variant;
begin
  aSomeText := 'Some text with single quote here '' and that''s it.';
  TDocVariant.New(aVarRes);
  TDocVariantData(aVarRes).AddValue('Display', aSomeText);
  _ObjAddProps(['test', aVarRes], Scope);
end;

The value of aVarRes in the debugger is:

'{"Display":"Some text with single quote here '' and that''s it."}'

In the view I have this in my script:

<script type="text/javascript">
	var aTest = '{{{Scope.test}}}';
	alert(aTest);
</script>

and I get:

<script type="text/javascript">
	var aTest = '{"Display":"Some text with single quote here ' and that's it."}';
	alert(aTest);
</script>

Which obviously raise an error.
If I try a string replace to replace all '' by \'' (the escape char in JS) like this before passing it to my variant:

aSomeText := StringReplace(aSomeText, '''', '\''', [rfReplaceAll]);

It seem that the char \ is escaped automatically like this:

value of "aSomeText" is: 'Some text with single quote here \'' and that\''s it.'
value of "aVarRes" is: '{"Display":"Some text with single quote here \\'' and that\\''s it."}'

Which obviously fail too..

edit:
and if I do this it work as expected: (but I can't in my use case build all the JSON by hand)

  aSomeText := '{"Display":"Some text with single quote here \'' and that\''s it."}';
  _ObjAddProps(['test', aSomeText], Scope);

I've tried a few others way but couldn't get it to work.
What would be the best way for me to achieve this ?

Thanks for your time !

Last edited by StxLog (2019-02-04 12:51:59)

Offline

#2 2019-02-04 17:06:20

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,659
Website

Re: Single quote and JSON in MVCApplication

Try to use double quotes in the JavaScript, and the JSONQuote helper:

var aTest = {{{JSONQuote Scope.test}}};

Offline

#3 2019-02-05 10:33:54

StxLog
Member
From: France
Registered: 2015-09-14
Posts: 58

Re: Single quote and JSON in MVCApplication

Oh great I didn't knew there was such helper. It work as expected thanks for your help !

This is what I ended-up with:

Delphi:
procedure TWebApp.Test(var Scope: Variant);
var
  aSomeText: RawUTF8;
  aVarRes: Variant;
begin
  aSomeText := 'Some text with single quote here '' and that''s it.';
  TDocVariant.New(aVarRes);
  TDocVariantData(aVarRes).AddValue('Display', aSomeText);
  _ObjAddProps(['test', aVarRes], Scope);
end;

JS:
<script type="text/javascript">
	var aTest = JSON.parse({{{JSONQuote Scope.test}}});
	alert(JSON.stringify(aTest));
</script>

Offline

Board footer

Powered by FluxBB