Parsing Json containing escape characters to JsonObject using Newtonsoft

I'm trying to parse json string to JsonObject but I'm having exception ("Bad JSON escape sequence: \x. Path 'original_query', line 8, position 35.")

I know there are bad characters in my JSON String but I'm not able to escape that characters.

Here is my working:

String json =  File.ReadAllText("json.txt");

JObject json = JObject.Parse(json);

Here is json file data:

{
"original_query" : "[currency == \x22USD\x22 \x26 ((exchange == \x22NASDAQ\x22) | (exchange == \x22NYSE\x22) | (exchange == \x22NYSEARCA\x22) | (exchange == \x22NYSEMKT\x22) | (exchange == \x22OTCBB\x22) | (exchange == \x22OTCMKTS\x22)) \x26 (forward_pe_1year \x3E= 0.00) \x26 (forward_pe_1year \x3C= 9.73)]",
"query_for_display" : "[currency == "USD" & ((exchange == "NASDAQ") | (exchange == "NYSE") | (exchange == "NYSEARCA") | (exchange == "NYSEMKT") | (exchange == "OTCBB") | (exchange == "OTCMKTS")) & (forward_pe_1year >= 0.00) & (forward_pe_1year <= 9.73)]"
}

I try to replace that characters:

//json = json.Replace("\x22", "\"");
//json = json.Replace("\x26", " ");
//json = json.Replace("\x3E", ">");
//json = json.Replace("\x3C", "<");

But it also give me same Exception.

Jon Skeet
people
quotationmark

Your attempt at replacing failed because you were using a C# string literal where \x is a C# escape sequence. You could have used something like:

json = json.Replace("\\x22", "\\\"");

... which would replace \x22 with \" in the text.

However, it looks like the text you're receiving actually includes a lot of \x escape sequences, so rather than replace them one by one, I'd do it in one go. Here's a short but complete program that works with the link you provided in chat:

using System;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;

class Test
{
    static void Main()
    {
        string text = File.ReadAllText("f.txt");
        text = Regex.Replace(text, @"\\x[0-9a-fA-Z]{2}", ConvertHexEscape);
        JObject obj = JObject.Parse(text);
        Console.WriteLine(obj);
    }

    static string ConvertHexEscape(Match match)
    {
        string hex = match.Value.Substring(2);
        char c = (char) Convert.ToInt32(hex, 16);
        // Now we know the character we're trying to represent,
        // escape it if necessary.
        switch (c)
        {
            case '\\': return @"\\";
            case '"': return "\\\"";
            default: return c.ToString();
        }
    }
}

people

See more on this question at Stackoverflow