Blankman
Blankman

Reputation: 267020

How to convert a string to JSON friendly string?

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?

Upvotes: 1

Views: 1488

Answers (2)

Mark Rutten
Mark Rutten

Reputation: 11

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

Upvotes: 1

Abion47
Abion47

Reputation: 24671

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.)

Upvotes: 2

Related Questions