I'm writing a selenium test which writes a JSON file to a CodeMirror window. Here's my code so far:
public void setJson(String jsonPath) throws IOException, InterruptedException {
// Read a file to a string
byte[] encoded = Files.readAllBytes(Paths.get(jsonPath));
String jsonText = new String(encoded, StandardCharsets.UTF_8);
// Get rid of line breaks
jsonText = jsonText.replace("\n", "");
// Escape the quotes
jsonText = jsonText.replace("\"", "\\\"");
// Write to the CodeMirror
WebElement queryInput = driver.findElement(By.xpath("//*[@id=\"content\"]/div/div[2]/div/div[1]/div[1]/div/div/div/div"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].CodeMirror.setValue(\"" + jsonText + "\");", queryInput);
}
This code works. But it writes the whole JSON file on one line. Here's a few things I tried.
Any ideas? I'm guessing there is a way to do this line by line, but I'd rather be able to just send the whole file as one string.
To get rid of line breaks
Try:
jsonText = jsonText.replaceAll("\n", "\\\\\\\\\\\\\\\\r\\\\\\\\\\\\\\\\n"); // for all occurrence
// This will replace \n with \\\\r\\\\n a new line for codemirror
or
jsonText = jsonText.replace("\n", "\\\\\\\\\\\\\\\\r\\\\\\\\\\\\\\\\n");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.