Skip to content

GROOVY I am getting random backslashes when creating JSON file in Folder

I am having trouble compiling the JSON file. This is my method (the main method just has the name of the method I am writing this code in it so I did not include the main method in here.)

static void buildJSONFiles() {
        String commandJson = "C:/Users/Name/Desktop/docfiles/command_config.json"
        def data = [
                        JsonOutput.toJson([new Commands(name:"upload", path:"${BUILTIN_EXE(command)}", includeCommandName: true),
                                           new Commands(name:"file_info", path:"${BUILTIN_EXE(command)}", includeCommandName: true)])


        def json_str = JsonOutput.toJson(data)
        def json_beauty = JsonOutput.prettyPrint(json_str)
        File file = new File(commandJson)


    static class Commands {
        String name
        String path
        boolean includeCommandName

my output in the console does come out right like this


but sending it to the JSON file it comes out like this


I understand that JSON backslash is a special character so I expected it to be only around the :”${BUILTIN_EXE(command)} but it is showing up everywhere where I did not even have a backslash.


You don’t have “random backslashes”, you have double-quoted JSON, since you’re using JsonOutput twice. json_str is a string with JSON in it, and then you’re wrapping that as a JSON value inside more JSON.