1

I have a string (text) that I would like to convert using a JSON parser so that it is javascript friendly.

In my view page I have some javascript that looks like:

var site = {
      strings: {
        addToCart: @someValue,

So @someValue should be javascript safe like double quotes, escaped chars if needed etc.

That value @someValue is a string, but it has to be javascript friendly so I want to parse it using JSON.

Does the new System.Text.Json have something?

I tried this:

return System.Text.Json.JsonDocument.Parse(input).ToString();

But this doesnt' work because my text is just a string, not a JSON string.

Is there another way to parse something?

2 Answers 2

2

The rules for escaping strings to make them JSON safe are as follows:

  • Backspace is replaced with \b
  • Form feed is replaced with \f
  • Newline is replaced with \n
  • Carriage return is replaced with \r
  • Tab is replaced with \t
  • Double quote is replaced with \"
  • Backslash is replaced with \\

And while it's not strictly necessary, any non-web-safe character (i.e. any non-ASCII character) can be converted to its escaped Unicode equivalent to avoid potential encoding issues.

From this, it's pretty straightforward to create your own conversion method:

public static string MakeJsonSafe(String s)
{
    var jsonEscaped = s.Replace("\\", "\\\\")
                       .Replace("\"", "\\\"")
                       .Replace("\b", "\\b")
                       .Replace("\f", "\\f")
                       .Replace("\n", "\\n")
                       .Replace("\r", "\\r")
                       .Replace("\t", "\\t");
    var nonAsciiEscaped = jsonEscaped.Select((c) => c >= 127 ? "\\u" + ((int)c).ToString("X").PadLeft(4, '0') : c.ToString());
    return string.Join("", nonAsciiEscaped);
}

DotNetFiddle

(Like I said, the nonAsciiEscaped stage can be omitted as it's not strictly necessary.)

Sign up to request clarification or add additional context in comments.

2 Comments

I wonder if there is a built-in method that does this for us?
@Blankman I'm not sure. On the one hand, it seems overly specific to need a string escaped for JSON in a setting where it isn't just part of an object that itself is being serialized to JSON, so I'd wonder what the benefit to going through the trouble of including such a method in the core library would be (particularly when it is custom-implemented easily enough by the few people who do actually need it). On the other hand, there are a fair amount of other methods that I would've thought too specific to put in the core library as well, so this one may exist somewhere too. Who knows?
1

A way to create a JSON safe string is to Serialize it with Newtonsoft.Json

string parsedJsonString = JsonConvert.SerializeObject(model.Content).Replace(@"""", "");

model.Content is of type string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.