How to loop through array elements within JSON string to create multiple products in Shopify order API

I’m trying to build an order through the Shopify API, but I need assistance with creating the JSON string dynamically. Here’s the code I have:

string orderString = @"
{
  ""order"": {
    ""line_items"": [
      {
        ""variant_id"": " + variantIdArray[0] + @",
        ""quantity"": " + quantityArray[0] + @"
      }
    ],
    ""customer"": {
      ""id"": 2750996643918
    },
    ""financial_status"": ""pending""
  }
}
";

Currently, I’m only able to add one product since I’m hardcoding the index [0]. I have two arrays (variantIdArray and quantityArray) and I want to loop through them to include multiple products in the line items. How can I use a for loop to achieve this while keeping it in string format for the API request?

totally agree, building JSON by hand is tough! try using StringBuilder or better yet, create objects and serialize them. here’s a quick example: var lineItems = new List<object>(); for(int i=0; i<variantIdArray.Length; i++) { lineItems.Add(new { variant_id = variantIdArray[i], quantity = quantityArray[i] }); } then serialize it with Newtonsoft or System.Text.Json.

Had the same issue when I started with Shopify’s API. Don’t build JSON strings manually - use a proper object structure instead. Create a dynamic object like this: var order = new { order = new { line_items = variantIdArray.Select((id, index) => new { variant_id = id, quantity = quantityArray[index] }).ToArray(), customer = new { id = 2750996643918 }, financial_status = "pending" } }; then use JsonConvert.SerializeObject(order) to get your JSON string. Way cleaner - no syntax errors and it handles the array iteration for you.

I’ve hit this same JSON issue before. String concatenation works fine if you build the line_items array first, then drop it into your main template. Loop through and construct the line items string separately: string lineItemsJson = ""; for(int i = 0; i < variantIdArray.Length; i++) { lineItemsJson += $"{{\"variant_id\": {variantIdArray[i]}, \"quantity\": {quantityArray[i]}}}"; if(i < variantIdArray.Length - 1) lineItemsJson += ","; } Watch your commas though - they’ll break the JSON if you mess up.