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.