Forum Discussion

DDS_Inc__Suppor's avatar
DDS_Inc__Suppor
Occasional Contributor
14 years ago

[Resolved]Adding "selective" commas to datasinks

I'm trying to use a datasource loop + datasink to create a json request. The request contains several repeating sections that require a comma in between them except for the last one. Is there a logical way to use a datasink to create?

Example of the final output needed:
{
{
"itemNum":20,
"rowNum":10,
"endDate":"12/31/2011"
},
{
"itemNum":30,
"rowNum":20,
"endDate":"12/31/2011"
},
{
"itemNum":40,
"rowNum":30,
"endDate":"12/31/2011"
}
}

3 Replies

  • Hi!

    I would do it like this:

    1. DataSource
    2. Groovy Script
    3. DataSource Loop
    4. DataSink

    Content of Groovy Script:

    def itemNum= context.expand( '${DataSource#itemNum}' )
    def rowNum= context.expand( '${DataSource#rowNum}' )
    def endDate= context.expand( '${DataSource#endDate}' )

    def newJsonElement= """{
    "itemNum":${itemNum},
    "rowNum":${rowNum},
    "endDate":${endDate}
    }"""

    if( context.allJsonElemens != null )
    {
    context.allJsonElemens.add( newJsonElement )
    }
    else
    {
    context.allJsonElemens = [ newJsonElement ]
    }

    def finalOutputNeeded = '{' + context.allJsonElemens.join(',') + '}'


    Then you can do whatever needed with finalOutputNeeded (store it to a Property, use it in a DataSink or Request, etc.).


    Hope this helps

    Henrik
    SmartBear Stockholm
  • DDS_Inc__Suppor's avatar
    DDS_Inc__Suppor
    Occasional Contributor
    Thank you. We a couple of minor tweaks (replaced "hej" with "allJsonElemens"), it worked perfectly. This solves quite a few problems I had generating sets of recurring data.
  • I updated Henriks post to fix the errors in the script, thanks for pointing them out!

    Regards,
    Dain
    SmartBear Sweden