Home > Uncategorized > Fix Malformed JSON in C#

Fix Malformed JSON in C#

When converting JSON to XML in C# using JsonReaderWriterFactory.CreateJsonReader, then you will find that it’s quite alot stricter at interpreting JSON than Javascript.

For Example { a:”b” } is valid JSON for javascript, but with JsonReaderWriterFactory.CreateJsonReader, it will return an error such as The token ‘”‘ was expected but found ‘a’.

This is some handy code that fixes malformed JSON for use with JsonReaderWriterFactory.CreateJsonReader, If Json is Malformed, i.e. no inverted commas around field names, then this function adds them back in

public static string NormalizeJson(string json)
{
    const string strFindRegex = @"(?[,{]\s*)(?\w+):";
    const string strReplaceRegex = @"${prefix}""${field}"":";
    var strWellFormedJson = Regex.Replace(json, strFindRegex, strReplaceRegex);
    // functions are valid in javascript, but not valid for a JsonReader
    const string strNoFunctionRegex = @"function..\s+{.*}";
    strWellFormedJson = Regex.Replace(strWellFormedJson, strNoFunctionRegex, "false");
    // Json should end with a close-curly-bracket
    if (!strWellFormedJson.EndsWith("}"))
    {
	var intLastCurlyBracket = strWellFormedJson.LastIndexOf("}");
	strWellFormedJson = strWellFormedJson.Substring(0, intLastCurlyBracket + 1);
    }
    return strWellFormedJson;
}
Advertisements
Categories: Uncategorized
  1. Y
    May 5, 2011 at 7:43 am

    It’s not working, error on line:

    var strWellFormedJson = Regex.Replace(json, strFindRegex, strReplaceRegex);

    Something is wrong with “strFindRegex” value.

  2. January 17, 2012 at 3:37 pm

    this works for me (c# 4.0)
    const string strFindRegex = @”(?[,{]\s*)(?\w+):”;
    const string strReplaceRegex = @”${prefix}””${field}””:”;

  3. January 17, 2012 at 3:40 pm

    lmfao some words are filtered in this shite….lets try again textual instead of arrows
    const string strFindRegex = @”(?{arrow left}prefix{arrow right}[,{]\s*)(?{arrow left}field{arrow right}\w+):”;
    const string strReplaceRegex = @”${prefix}””${field}””:”;

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: