Script Page - CSV to HtmlDump

Assuming I have the contents of a CSV file I want to transform this to a format to easily do an htmlDump but I can’t seem to figure out in the script to get it from
System.Collections.Generic.List1[System.Collections.Generic.List1[System.String]] to the correct format:

	{{ csvData | parseCsv | to => d}}
{{d}}

That outputs the generic list type info above so that’s what we have. csvData is just a read in string from a file.

I’d like to just do:

{{ d | htmlDump}}  // won't work as is 

but need to map it or do something else first?

Convert each column into an object with named properties, see the {{csv}} block example.
https://sharpscript.net/docs/blocks#csv

{{#csv cars}}
Tesla,Model S,79990
Tesla,Model 3,38990
Tesla,Model X,84990
{{/csv}}
{{ cars |> map => { Make: it[0], Model: it[1], Cost: it[2] } |> htmlDump }}
Total Cost: {{ cars |> sum => it[2] |> currency }}

Also please transition to use the |> pipe forward operator as support for the old syntax may eventually be dropped.

Thanks for the pointers here. I am using the new pipe going forward that was just an old script I was testing on.

The problem with this is the csv’s are dynamic and the example lacks all the preprocessing to get the header row/etc. The example I reviewed prior but it is hard coded and I just couldn’t seem to figure out how to get it all to work. In my example csvData is the csv file content with header row.

I guess there is no easy way. Ended up just building the table manually for now which was a little more work but straightforward. I was just hoping to easily use htmlDump since that utility is so nice and can easily just be styled.

Here’s a simple function to convert it into a list of named objects in #Script, e.g:

{{#csv cars}}
Make,Model,Cost
Tesla,Model S,79990
Tesla,Model 3,38990
Tesla,Model X,84990
{{/csv}}

{{#function convertCsv(csv) }}
  var headers = csv.take(1)[0]
  var lines   = []
  #each row in csv.skip(1)
    var to = {}
    #each headers
      to[it] = row[index]
    /each
    lines.push(to)
  /each
  return(lines)
{{/function}}

{{ convertCsv(cars) |> htmlDump }}

It should be easier to implement convertCsv in a C# Script Method that takes List<List<string>> and convert it to a list of named Key/Value Pairs in a List<Dictionary<string,string>>.

1 Like

Thank you, I really enjoy the script support but sometimes struggle trying to figure out the best way to do something. I was going to look at creating a custom method but this is all done on a razor view in umbraco and didn’t want to overcomplicate it. Quite frankly, the scripting support is so awesome I rarely need to.

Again, thanks!

1 Like