Search code examples
jsonloopsvbscriptasp-classic

Trim the last character at the end of string


I have a loop that is creating a string until the end of the file. Depending on how many products I have at the time. I need to trim the last comma at the end.

I get:

{ sku: '6200', display_name:'Product 1', unit_price: 497.37, qty: 1 },  
{ sku: '2344', display_name:'Product 2', unit_price: 824.21, qty: 1 },

I need:

{ sku: '6200', display_name:'Product 1', unit_price: 497.37, qty: 1 },  
{ sku: '2344', display_name:'Product 2', unit_price: 824.21, qty: 1 }

Loop:

<%
set rsheadercart = db.execute(sqlheadercart)
    if not rsheadercart.eof then 
        do until rsheadercart.eof 




            items = items & " { sku: '" & rsheadercart("ten_digit_part_number") & "',"
            items = items & " display_name:'" & rsheadercart("part_name") & "',"
            items = items & " unit_price: " & rsheadercart("price") & ","
            items = items & " qty: " & rsheadercart("quantity") & " }, "


        rsheadercart.movenext
        loop 
        %>
<%
end if 
%>

Solution

  • Move your comma to the beginning of the loop and put it in a conditional statement so that it isn't executed at the first iteration

    do until rsheadercart.eof 
    
        If items <> "" then 
           items = items & ","
        End If     
    
        items = items & " { sku: '" & rsheadercart("ten_digit_part_number") & "',"
        items = items & " display_name:'" & rsheadercart("part_name") & "',"
        items = items & " unit_price: " & rsheadercart("price") & ","
        items = items & " qty: " & rsheadercart("quantity") & " } "
    
    rsheadercart.movenext
    loop