· Jul 5, 2018

How can I convert CSV to JSON

it is possible to convert a csv file to json file?

I want to stream json files and output the data as it comes in from the files. So my files are "csv" type and I want to convert these files to "json" type.

I can read csv file as follows:

ClassMethod ReadFile()
    set stream = ##class(%Stream.FileCharacter).%New()
    set sc = stream.LinkToFile("*.csv")
    do stream.Rewind()
    while'stream.AtEnd {
        set line=stream.ReadLine()
        write line,!

What should I add to convert it to "json" and read it again?

Thank you

Discussion (7)3
Log in or sign up to continue

This is one of those things that becomes dead easy when you use Node.js (and use QEWD to integrate Cache with Node).  There's almost always a tried and tested module out there already that will do the stuff you want, eg in this case:

And once in JSON format, you can transform it to whatever other JSON format you want using:

Example of converting a CSV to JSON file and then reading from a JSON file without creating intermediate classes/tables:

  ; CSV -> JSON

  rowtype "name VARCHAR(50),year INTEGER,amount NUMERIC(9,2),date DATE",
    fileIn "C:\Temp\import.csv",
    fileOut "C:\Temp\export.json",

  obj.loadResultSet(##class(%SQL.Statement).%ExecDirect(,"call %SQL_Util.CSV(,?,?)",.rowtype,.fileIn),"res"),

  ; Read JSON

  obj ##class(%DynamicAbstractObject).%FromJSON(fileImp)
  !,"obj.res.%Size() = ",obj.res.%Size()



obj.res.%Size() = 2