Forum Discussion

henil_shah's avatar
henil_shah
Contributor
6 years ago

Create json in Groovy

Need to create Json like this

"data":

{

"data1":"data1",

"data2":"data2"

}

}

 

I'm able to create the below one but not the above one. I'm using def json = new JsonOutput().toJson(obj) for the below

{

"data1":"data1",

"data2":"data2"

}

  • nmrao's avatar
    nmrao
    6 years ago

    henil_shah 

     

    Would you please check this script 

    You may test it online in the above link.

    import static groovy.json.JsonOutput.toJson
    import static groovy.json.JsonOutput.prettyPrint
    def data = [data1: "data1", data2: "data2"]
    def jsonString = prettyPrint(toJson(data: data).toString())
    log.info jsonString
  • nmrao's avatar
    nmrao
    Champion Level 3
    Creating that would not be difficult. What I am curious is more context to the problem. How are you getting the input data and how it is going to be used.
    • Olga_T's avatar
      Olga_T
      SmartBear Alumni (Retired)

      Hi all,

       

      henil_shah, have you managed to accomplish the task?

      If you haven't, could you please provide the information that nmrao requested?

      Thanks in advance.

       

    • henil_shah's avatar
      henil_shah
      Contributor

      Input data will be in Groovy script with random data provided to a test case. I'm able to create simple Json but not this kind of Json

      • nmrao's avatar
        nmrao
        Champion Level 3

        henil_shah 

         

        Would you please check this script 

        You may test it online in the above link.

        import static groovy.json.JsonOutput.toJson
        import static groovy.json.JsonOutput.prettyPrint
        def data = [data1: "data1", data2: "data2"]
        def jsonString = prettyPrint(toJson(data: data).toString())
        log.info jsonString