首页 > 解决方案 > Inno Setup:如何从 JSON 文件的子部分编辑和检索值

问题描述

我正在创建一个安装程序,我需要从 JSON 文件中编辑和检索值。

Section_2作品中检索和编辑值很好。问题是从Section_1. 下面我们可以看到一个例子:

{
  "Section_1": {
    "children_1": {
      "children_1_1": "value_1",
      "children_1_2": "value_2"      
    },
    "children_2": "blablabla"
  },  
  "Section_2": {
    "children_2_1": "value_1",
    "children_2_2": "value_2"   
  }    
}  
[Files]
Source: "{#ProjectUrl}\JSONConfig.dll"; Flags: dontcopy

[Code]
var 
  FileName: WideString;  
  StrValue: WideString;
  StrLength: Integer; 

function JSONQueryString(FileName, Section, Key, Default: WideString;
  var Value: WideString; var ValueLength: Integer): Boolean;
  external 'JSONQueryString@files:jsonconfig.dll stdcall'; 

function JSONWriteString(FileName, Section, Key, 
  Value: WideString): Boolean;
  external 'JSONWriteString@files:jsonconfig.dll stdcall';

function editAppSettingsJson(Section_1: String; Section_2:String): Boolean;   
begin
  FileName := '{#AppSettingsJsonFile}'; 
  SetLength(StrValue, 16);  
  StrLength := Length(StrValue);

  Result := True;
  { Does not work. How can I edit it? }
  if not JSONWriteString(FileName, 'children_1', 'children_1_1', 
  Section_1) then
  begin
    MsgBox('JSONWriteString Section_1:children_1:children_1_1 failed!', 
    mbError, MB_OK);
    Result := False;
  end; 
  { Works fine. }
  if not JSONWriteString(FileName, 'Section_2', 'children_2_1', Section_2) 
  then
  begin
    MsgBox('JSONWriteString Section_2:children_2_1 failed!', mbError, 
    MB_OK);
    Result := False;
  end;       
end;  

procedure InitializeWizard;
var  
  value_1: String;
  value_2: String;  
begin    
  value_1:= 'value_2';
  value_2:= 'value_3';

  editAppSettingsJson(value_1, value_2);
end; 

提前非常感谢您的支持。

问候,迭戈维亚

标签: jsoninno-setuppascalscript

解决方案


我不认为它JSONConfig.dll支持嵌套结构。

您可以改用JsonParser 库。它可以解析嵌套结构。虽然它不像JSONConfig.dll- 那样容易使用,因为它更通用。

以下代码将执行以下操作:

var
  JsonLines: TStringList;
  JsonParser: TJsonParser;
  JsonRoot, Section1Object, Children1Object: TJsonObject;
  Child11Value: TJsonValue;
begin
  JsonLines := TStringList.Create;
  JsonLines.LoadFromFile(FileName);

  if ParseJsonAndLogErrors(JsonParser, JsonLines.Text) then
  begin
    JsonRoot := GetJsonRoot(JsonParser.Output);
    if FindJsonObject(JsonParser.Output, JsonRoot, 'Section_1', Section1Object) and
       FindJsonObject(JsonParser.Output, Section1Object, 'children_1', Children1Object) and
       FindJsonValue(JsonParser.Output, Children1Object, 'children_1_1', Child11Value) and
       (Child11Value.Kind = JVKString) then
    begin
      Log(Format('children_1_1 previous value %s', [
        JsonParser.Output.Strings[Child11Value.Index]]));
      JsonParser.Output.Strings[Child11Value.Index] := 'new value';

      JsonLines.Clear;
      PrintJsonParserOutput(JsonParser.Output, JsonLines);
      JsonLines.SaveToFile(FileName);
    end;
  end;
end;

该代码使用我对如何在 Inno Setup 中解析 JSON 字符串的回答中的函数?


推荐阅读