Alternative to using StringReplace to remove unwanted characters from a JSON response

I am working on a small project that requires me to parse a JSON file and post the results in a database. I use SuperOjbect to parse the file and generate the results, but I hit the notepad a bit and could use some help.

Here is an example JSON file that I need to parse. In fact, these files contain more information than this, but this is only to give you an example of what types of data I work with.

{
    "id" : 1,
    "object" : "value",
    "colors" : ["red", "green", "blue"],
}

Here is an example of the code that I use to parse part of a file (an array in this case).

var
  jo : ISuperObject;
begin
  jo := TSuperObject.ParseFile('response.txt', TRUE);
  ShowMessage(jo['colors'].AsString);
end;

, : ["red", "blue", "green"], StringReplace []", , red, green, blue, , , , StringReplace, , JSON, , . ?

+4
1

, colors - , , Copy() . ". :

  • StringReplace(), :

    var
      jo : ISuperObject;
      s: string;
    begin
      jo := TSuperObject.ParseFile('response.txt', TRUE);
      s := jo['colors'].AsString;
      s := Copy(s, 2, Length(s)-2);
      s := StringReplace(s, '"', '', [rfReplaceAll]);
      ShowMessage(s);
    end;
    
  • TStringList. QuoteChar ", , CommaText:

    var
      jo : ISuperObject;
      sl: TStringList;
      s: string;
    begin
      jo := TSuperObject.ParseFile('response.txt', TRUE);
      s := jo['colors'].AsString;
      sl := TStringList.Create;
      try
        sl.CommaText := Copy(s, 2, Length(s)-2);
        s := sl.CommaText;
      finally
        sl.Free;
      end;
      ShowMessage(s);
    end;
    

, . , :

var
  jo : ISuperObject;
  arr: ISuperObject;
  sl: TStringList;
  i: Integer;
  s: string;
begin
  jo := TSuperObject.ParseFile('response.txt', TRUE);
  arr := jo['colors'].AsArray;
  sl := TStringList.Create;
  try
    for i := 0 to arr.Length-1 do
      sl.Add(arr.S[i]);
    s := sl.CommaText;
  finally
    sl.Free;
  end;
  ShowMessage(s);
end;
+3

Source: https://habr.com/ru/post/1548429/


All Articles