www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Encode string as json string

reply tcak <1ltkrs+3wyh1ow7kzn1k sharklasers.com> writes:
Other than generating normal JSON content (stringify), JSON 
string is used for Javascript string expressions as well.

To create a properly encoded Javascript string, the shortest way 
is

JSONValue("this'\\is//the\"text").toString();

Yes, it works, but it is uncomfortable to write the code as 
above. Two issues:

1. It creates a struct, and there are extra processing in the 
background (check the source code for this.)

2. It is really long.

std.json already has a string encoding function in it, but it is 
not exposed outside.

https://github.com/D-Programming-Language/phobos/blob/master/std/json.d#L1002

It would be quite useful to expose this function for ease of use. 
Any thoughts?
Feb 15 2016
parent Jonathan M Davis <jmdavisProg gmx.com> writes:
On Monday, 15 February 2016 at 14:09:04 UTC, tcak wrote:
 Other than generating normal JSON content (stringify), JSON 
 string is used for Javascript string expressions as well.

 To create a properly encoded Javascript string, the shortest 
 way is

 JSONValue("this'\\is//the\"text").toString();

 Yes, it works, but it is uncomfortable to write the code as 
 above. Two issues:

 1. It creates a struct, and there are extra processing in the 
 background (check the source code for this.)

 2. It is really long.

 std.json already has a string encoding function in it, but it 
 is not exposed outside.

 https://github.com/D-Programming-Language/phobos/blob/master/std/json.d#L1002

 It would be quite useful to expose this function for ease of 
 use. Any thoughts?
I've been using http://code.dlang.org/packages/std_data_json instead, and it's in the running to be a replacement for std.json (though I don't know quite what the status of all that it is; it was reviewed but still had work it needed IIRC). It's worked well enough for me and might do better for you than std.json. I don't know though. I pretty much only use JSON when I have to. - Jonathan M Davis
Feb 15 2016