More fun with Std_Out: convert .csv to .json

Started by spl, March 23, 2026, 11:45:11 AM

Previous topic - Next topic

spl

Another quick script. WB has an Extender and functions to read and process Json, but not a lot (as far as I have seen) to create json. Many of the examples that have been posted here, and I have done a few, involve data arrays with a descriptive 'header' and a "count": element. CSV data is especially adaptable to json output. I have attached a sample csv to accompany the code below. I think ArrayFileGet() for the csv might make it possible to not need the PS boost, but would take some effort. Below is painless, mostly writes itself:

[EDIT]: I forgot, WB only allows specific file uploads. Rename Products.txt to Products.csv to test the script. Of course, I doubt anyone will test it.

;Output csv data to Json with Count and data title (based on FileRoot() of csv)
;Displays Json return as text file - [save script as StdOut_CSVtoJson.wbt]
;Stan Littlefield 3/23/2026
;========================================================================================================================
Gosub udfs
;using preset csv file
csv = Dirscript():"Products.csv"
;you can test with any csv file with
;types="CSV Files|*.csv|"
;csv=AskFilename("SelectFile", Dirscript(), types,, 1)
;
If !fileexist(csv) Then Terminate(@TRUE,"Cannot load CSV",csv)
jfile = StrReplace(csv, ".csv", ".json")
If fileexist(jfile) Then filedelete(jfile)
header= FileRoot(csv) ;or could be anything you choose
args = $"$json = import-csv [csv]
$cnt = $json.Count
$repl = [PSCustomObject]@{
   [header] = $json
   Count = $cnt
} | ConvertTo-Json

$repl
$"
args = StrReplace(args,"[csv]",csv)
args = StrReplace(args,"[header]",header)
cmd="Powershell"
msg='Product CSV to JSON'
BoxOpen("Running...",cmd:" ":args:@LF:"PLEASE WAIT...MAY TAKE SOME TIME")
TimeDelay(2)
vals = Get_stdout()
FilePut(jfile,vals) 
If FileExist(jfile) Then Run("notepad.exe",jfile)
Exit
;======================================================================
:udfs
#DefineSubroutine Get_stdout()
ObjectClrOption("useany","System")
objInfo = ObjectClrNew("System.Diagnostics.ProcessStartInfo")
Output=""
timeOut = ObjectType("I2",5000)
objInfo.FileName = cmd
objInfo.RedirectStandardError = ObjectType("BOOL",@TRUE)
objInfo.RedirectStandardOutput = ObjectType("BOOL",@TRUE)
objInfo.UseShellExecute = ObjectType("BOOL",@FALSE)
objInfo.CreateNoWindow = ObjectType("BOOL",@TRUE)
objInfo.Arguments = args
oProcess = ObjectClrNew("System.Diagnostics.Process")
oProcess.StartInfo = objInfo
BoxShut()
oProcess.Start()
oProcess.WaitForExit(timeout)
STDOUT = oProcess.StandardOutput.ReadToEnd()
STDERR = oProcess.StandardError.ReadToEnd()
Output = Output:STDOUT:@CRLF
If STDERR<>""
  Output = Output:"STDERR:":STDERR:@CRLF
Endif
oProcess = 0
objInfo = 0

Return (Output)
#EndSubroutine
Return
;==========================================================
Stan - formerly stanl [ex-Pundit]

SMF spam blocked by CleanTalk