2
void f(string message)
{
    string.Format(message,"x",y");
}

f() is called by g:

g()
{
   f(SomeJson+"{0}");
}

the curly braces in json are being interpreted as placeholders for values by string.format() in f(). IS there a way to have the curly braces escaped?

Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
Aadith Ramia
  • 10,005
  • 19
  • 67
  • 86
  • It's hard to be sure, but I suspect his question is slightly different to the suggested duplicate. He wants to escape the characters in a generated string, not the string literal he has used. – Ergwun Sep 18 '13 at 08:02
  • Just append the formatted string to `SomeJson` **after** formatting. – Ergwun Sep 18 '13 at 08:07

1 Answers1

9

Double them up:

f(SomeJson+"{{0}}");

Or replace them in the JSON, if that's what you need:

f(SomeJson.Replace("{", "{{")
    .Replace("}", "}}") + "{0}");

You could also delegate this job to an extension method:

public static class StringExtensions
{
    public static string EscapeBraces(this string s)
    {
        return s.Replace("{", "{{")
                .Replace("}", "}}");
    }
}

f(SomeJson.EscapeBraces() + "{0}");

Or, as Ergwun says, you could simply concatenate the values afterwards. My assumption, though, is that that's less straightforward in your actual code than in this trivial example.

Ant P
  • 24,820
  • 5
  • 68
  • 105
  • 1
    If it is the braces in the JSON that he wants to escape, he's actually better off concatenating the strings after he has performed the variable substitutions. No escaping required. – Ergwun Sep 18 '13 at 08:05
  • @Ergwun Very true. Unless, of course, `f` is less trivial than he's making out. – Ant P Sep 18 '13 at 08:07
  • Yeah, the fact he has a single substitution, but two parameters in the code in his question does open that possibility. But if he's generating format strings from JSON, then that's a whole separate problem! – Ergwun Sep 18 '13 at 08:27