Skip to content

Experimental: Mini CSV Extension

Jeremy B edited this page Feb 5, 2019 · 2 revisions

The mini-csv extension provides convenience primitives for reading data from delimited strings to NetLogo lists, and for converting NetLogo lists to string values.

There are four primitives.

  • mini-csv:to-string - convert a "two dimensional" list of lists into a string value.
  • mini-csv:from-string - convert a string into a list of lists with values.
  • mini-csv:to-row - convert a "one dimensional" list into a string value.
  • mini-csv:from-row - convert a string into a list of values.

Simple Usage

If you're working with whole files with data on separate rows, or you want to generate such a file, you want to-string and from-string:

observer> mini-csv:from-string ""
observer: []
observer> mini-csv:to-string []
observer: ""
observer> mini-csv:from-string "apples,oranges,1,2\ngreen,red,3,4"
observer: [["apples" "oranges" 1 2] ["green" "red" 3 4]]
observer> mini-csv:to-string [[ "apples" "oranges" 1 2 ] ["green" "red" 3 4]]
observer: "apples,oranges,1,2\ngreen,red,3,4"

If you're working one row at a time with single lists, you want to-row or from-row:

observer> mini-csv:from-row ""
observer: []
observer> mini-csv:to-row []
observer: ""
observer> mini-csv:from-row "14,10,-2"
observer: [14 10 -2]
observer> mini-csv:to-row [14 10 "delim,here"]
observer: "14,10,\"delim,here\""

Values

Only values that can be easily converted to strings will be correctly handled by to-string and to-row. Simple values like numbers, strings, and true/false should all be correctly converted. Complex values like anonymous procedures or turtles will probably not be well-represented. I recommend "pre-converting" any complex values you want to retain:

observer> create-turtles 3 [ fd 20 set label "hi, how are ya?" ]
observer> mini-csv:to-string (list (sort turtles) )
observer: "(turtle 0),(turtle 1),(turtle 2)" ; not very useful
observer> mini-csv:to-string [ (list who pxcor pycor color label) ] of turtles ; convert each turtle into a list of values we want
observer: "1,-3,-2,85,\"hi, how are ya?\"\n0,-4,2,85,\"hi, how are ya?\"\n2,-5,3,65,\"hi, how are ya?\""

Delimiters

All primitives also accept an optional delimiter argument, which is a string of a single character used to separate individual values. Because the delimiter is optional, when you add one you must surround the whole primitive usage with parenthesis. Examples:

observer> (mini-csv:from-string "1|2|3\n4|5|6" "|")
observer: [[1 2 3] [4 5 6]]
observer> (mini-csv:to-row [14 10 "red,blue" "red"] "|")
observer: "14|10|red,blue|red"
You can’t perform that action at this time.