简体   繁体   中英

How to format json in a file using Groovy

I have a question in regards to formatting a file so that it displays a Json output to the correct format.

At the moment the code I have below imports a json into a file but when I open the file, it displays the json in a single line (word wrap unticked) like so:

{"products":[{"type":null,"information":{"description":"Hotel Parque La Paz (One Bedroom apartment) (Half Board) [23/05/2017 00:00:00] 7 nights","items":{"provider Company":"Juniper","provider Hotel ID":"245","provider Hotel Room ID":"200"}},"costGroups":[{"name":null,"costLines":[{"name":"Hotel Cost","search":null,"quote":234.43,"quotePerAdult":null,"quotePerChild":null}

I want to format the json in the file so that it looks like actual json formatting like so:

{
  "products": [
    {
      "type": null,
      "information": {
        "description": "Hotel Parque La Paz (One Bedroom apartment) (Half Board) [23/05/2017 00:00:00] 7 nights",
        "items": {
          "provider Company": "Juniper",
          "provider Hotel ID": "245",
          "provider Hotel Room ID": "200"
        }
      },
      "costGroups": [
        {
          "name": null,
          "costLines": [
            {
              "name": "Hotel Cost",
              "search": null,
              "quote": 234.43,
              "quotePerAdult": null,
              "quotePerChild": null
            }

Virtually each header has its own line to contain its values.

What is the best way to implement this to get the correct json formatting within the file?

Below is the code:

    def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context) 
    def dataFolder = groovyUtils.projectPath +"//Log Data//"
    def response = testRunner.testCase.getTestStepByName("GET_Pricing{id}").getProperty("Response").getValue();
    def jsonFormat = (response).toString()
    def fileName = "Logged At - D" +date+ " T" +time+ ".txt"
    def logFile = new File(dataFolder + fileName)


    // checks if a current log file exists if not then prints to logfile

    if(logFile.exists())
    {

     log.info("Error a file named " + fileName + "already exisits")
    }
        else
    {

     logFile.write "Date Stamp: " +date+ " " + time + "\n" + jsonFormat //response

如果您具有现代的groovy版本,则可以执行以下操作:

JsonOutput.prettyPrint(jsonFormat)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM