Mount Regex to change string json

Asked

Viewed 197 times

1

I have the following string, which will actually be treated as a json, stored in a column in the database in my SQL Server:

{"PT":"adssadsadsd "asdada"","ES":"","FR":"","EN":""}

How do I automatically change the string to look like the following:

{"PT":"adssadsadsd \"asdada\"","ES":"","FR":"","EN":""}

I want to make that change in Controller of my project MVC. I need this because I have records in the database that are badly formatted and then I can’t get the information in the right way.

  • before mounting your JSON you can call string.Replace("\"", "\\\"")

  • That won’t change all the quotes instead of just changing the ones I mentioned?

  • if you place after the Json is mounted the answer is yes. , if you can[ivel put the code that generates the JSON there I can tell you for sure.

  • but I can’t do Parse because of those quotes, give me Exception

  • you’re storing the entire JSON in your database field? That’s it?

  • exact! I don’t know it’s the best, but it was already like this when I picked up the project

Show 1 more comment

1 answer

0


Rode in Fiddle with an idea. It’s not exactly the best, but it’s based on the idea that if I replace the initial quotation marks with apostrophes and serialize, the JSON deserializer will understand that the quotation mark is part of the field, not a delimiter.

public static IEnumerable<String> RetirarAspas(string jsonString) 
{
    var regex = new Regex("(\")([\\w]+)(\")(:)(\")([\\w\\s\"]*)(\"),?");
    var teste = regex.Matches(jsonString);

    foreach (Match match in teste) 
    {
        String linha = "";

        for (int i = 1; i < match.Groups.Count; i++) 
        {
            if (match.Groups[i].ToString() == "\"") 
                linha += "'";
            else
                linha += match.Groups[i].ToString();
        }

        yield return linha;
    }
}

Then I can build JSON like this:

    var testeJson = "{";
    foreach (var linha in lista)
    {
        Console.WriteLine(linha);
        testeJson += linha + ", ";
    }

    testeJson += "}";

    var jsonDesserializado = JsonConvert.DeserializeObject<dynamic>(testeJson);
    Console.Write(jsonDesserializado);
  • how do I include '-' in strings?

  • Only change regular expression: new Regex("(\")([\\w-]+)(\")(:)(\")([\\w\\s\"-]*)(\"),?");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.