Escape curly braces when using String.Format or StringBuilder.AppendFormat

I was using the StringBuilder to create a JSON string which included an array and therefore curly braces, but I got an exception as curly braces are used to define the parameters for the format.

sb.AppendFormat("{\"Forename\":\"{0}\",\"Surname\":\"{1}\"}", person.Forename, person.Surname);

At first I tried adding a backslash which is used to escape the quotation mark but this didn’t work, so I tried the double character trick but adding two curly braces which seems to do the job.

sb.AppendFormat("{{\"Forename\":\"{0}\",\"Surname\":\"{1}\"}}", person.Forename, person.Surname);
Posted on by Joe in C#, JavaScript

2 Responses to Escape curly braces when using String.Format or StringBuilder.AppendFormat

  1. marky-b

    Great post. I kept trying “\” but couldn’t figure it out. Thanks

  2. Gavin

    Thanks mate.

Add a Comment