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

delphi, json, superobject

Solution

Since you know `colors` is an array, and an array is always stringified with brackets, just use `Copy()` to remove the brackets. As for removing the `"` characters. You have a couple of options:

use `StringReplace()`, like you already know:

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;

use a `TStringList`. Its default `QuoteChar` is `"`, so it can parse out the quoted values for you using its `CommaText` property:

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;

Alternatively, don't stringify the entire array at all. Iterate through the array extracting the individual values you need:

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;

Problem

I am working on a small project that that requires me to parse a JSON file and place the results in a database. I am using SuperOjbect to parse the file and generate the results, but I have hit a bit of a roadblock and could use some assistance. Here is an example of a JSON file that I a need to parse. In reality these files contain more information than this, but this is just to give you an example of what type of data I am working against. ``` { "id" : 1, "object" : "value", "colors" : ["red", "green", "blue"], } ``` Here is an example of the code I am using to parse a portion of the file (an array in this case). ``` var jo : ISuperObject; begin jo := TSuperObject.ParseFile('response.txt', TRUE); ShowMessage(jo['colors'].AsString); end; ``` Which results in a string that looks like this: `["red", "blue", "green"]` and then I use the StringReplace function to remove all the `[]"`characters so I am left with a string that now looks like this `red, green, blue` and this works fine, but I am searching for an alternative to this method that was more designed for this sort of thing rather than rely on the StringReplace function, which could cause unforseen problems if the JSON file I need to parse is more complex. Any Ideas ?

Original source