Corriger une string JSON en Qt

Publié dans Snippet | Marqué avec , ,

La méthode ci-dessous permet d’autoriser une syntaxe moins rigoureuse en prenant soin de modifier les petites erreurs qui ont pu être commises.

 * Clean a string
 * * Remove comments ("//" and "/*")
 * * Add first and last braces ("{" and "}") if missing
 * * Remove unauthorized commas
 * @param data Almost JSON string that will be cleaned to become a valid JSON string
 * @return Valid JSON string (or at least, a more valid one)
QString cleanJsonString(QString data)
    // Remove inline comms
    QRegExp pattern = QRegExp("(^|\\[|\\{|,|\\n|\\s)//.*($|\\n)");
    pattern.setMinimal(true); //ungreedy
    data.replace(pattern, "\\1\n");
    data.replace(pattern, "\\1\n"); //2 times, I am not sure why...
    // Remove bloc comms
    pattern = QRegExp("/\\*.*\\*/");
    pattern.setMinimal(true); //ungreedy
    data.replace(pattern, "");
    // Add first and last brace
    if (!data.startsWith("{")) {
        data = "{\n"+data;
    if (!data.endsWith("}")) {
        data += "\n}";
    // Remove commas before } or ]
    pattern = QRegExp(",(\\s*[}\\]])");
    pattern.setMinimal(true); //non-greedy
    data.replace(pattern, "\\1");
    return data;

J’ai commis une méthode similaire en PHP : Manipuler du JSON en PHP.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>