Forum Discussion

Sirisha2020's avatar
Sirisha2020
Contributor
2 years ago

Hi, I want to format all the json files in a folder using groovy script. can someone please help me.

Hi,

 

I want to format all the json files in a folder using groovy script. can someone please help me. I tried with pretty print method it is not working.

Method used is as below :

printResponseWriter.prettyprint(jsonResponseContent).

 

Thanks.

 

3 Replies

  • try this.

     

    import groovy.json.*;

    def jsonSlurper = new JsonSlurper()
    String filePath = "C:\\result.json"
    def object = jsonSlurper.parse(new File(filePath))

    def json = JsonOutput.toJson(object)
    def pretty = JsonOutput.prettyPrint(json)

     

     

    • Sirisha2020's avatar
      Sirisha2020
      Contributor

      Hi,

      Thanks for the solution.  Formatted text is printing on the console. But can we format file itself. Please let me know on this.

       

      Thanks

      • Shashavali's avatar
        Shashavali
        Contributor

        Sirisha2020 

         

        try this

         

        import groovy.json.*;

        def jsonSlurper = new JsonSlurper()
        String filePath = "C:\\DevCode\\lgs-nimbus\\result.json"
        def object = jsonSlurper.parse(new File(filePath))

        def json = JsonOutput.toJson(object)
        def pretty = JsonOutput.prettyPrint(json)
        File file = new File(filePath)
        file.write(pretty)