简体   繁体   中英

Generate JSON Array from CSV or Database

I am looking to create a JSON array from a CSV or Database. How would I format my source data or does anyone have advice/links to tutorials for either creating a .NET Web Service or another method to generate JSON from a CSV or database? An example array is below.

Example:

{
section1: [
{
"id":1,
"title":mytitle1
}
],
{
section2: [
{
"id":2,
"title":mytitle2
}
], etc.....

I would first convert my csv file to an object, then parse the object to JSON using newtonsoft's json class

Check this out to learn how to transform CSV to object

Go here to get newtonsoft's json.net tools (can be done using nuget)

function GetImageToJson:string; var Q,Q1:TSQLQuery; content,Liststr : String; NextRecord : Integer; begin content :='['; Liststr :=''; Q := TSQLQuery.Create(nil); Q.Database := dmDatabase.IBConnection; Q.SQL.Text := 'SELECT ID,TB,NAME FROM V_IMAGES'; Q.Open; Q.First; NextRecord :=0; if not Q.Fields[0].IsNull then begin while not Q.eof do begin if (NextRecord =1) then Liststr :=Liststr +','; Liststr := Liststr + '{"ID" : "' +Q.Fields[0].AsString+'",'+ '"TB" : "' +Q.Fields[1].AsString+'",'+ '"NAME" : "'+Q.Fields[2].AsString+ '"}'; NextRecord :=1; Q.Next; end;

  end;
  Q.Free;

  Q := TSQLQuery.Create(nil);
  Q.Database := dmDatabase.IBConnection;
  Q.SQL.Text :=
    'SELECT * FROM sETUP';
  Q.Open;
  Q.First;

  if not Q.Fields[0].IsNull then begin
    while not Q.eof do begin
       if (NextRecord =1) then
           Liststr :=Liststr +',';

       Liststr := Liststr + '{"'+Q.Fields[0].DisplayName+'" : "'        +Q.Fields[0].AsString+'",'+
                         '"'+Q.Fields[1].DisplayName+'" : "'  +Q.Fields[1].AsString+'",'+
                         '"'+Q.Fields[2].DisplayName+'" : "'  +Q.Fields[2].AsString+'",'+
                         '"'+Q.Fields[3].DisplayName+'" : "'  +Q.Fields[3].AsString+'",'+
                         '"'+Q.Fields[4].DisplayName+'" : "'  +Q.Fields[4].AsString+'",'+
                         '"'+Q.Fields[5].DisplayName+'" : "'  +Q.Fields[5].AsString+'",'+
                         '"'+Q.Fields[6].DisplayName+'" : "'  +Q.Fields[6].AsString+'",'+
                         '"'+Q.Fields[7].DisplayName+'" : "'  +Q.Fields[7].AsString+'",'+
                         '"TB":"setup"'+
                   '}';

       NextRecord :=1;
       Q.Next;
    end;

  end;
  Q.Free;


  content := content +Liststr+ ']';
  result  := content;

end;  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM