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; }
Categories: Uncategorized
It’s not working, error on line:
var strWellFormedJson = Regex.Replace(json, strFindRegex, strReplaceRegex);
Something is wrong with “strFindRegex” value.
LikeLike
this works for me (c# 4.0)
const string strFindRegex = @”(?[,{]\s*)(?\w+):”;
const string strReplaceRegex = @”${prefix}””${field}””:”;
LikeLike
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}””:”;
LikeLike