USEGEAR

导航

学习unigui【27】像pg的jsonb一样编辑json。

var
  I: Integer;
  CurrentObject: TJSONObject;
  FieldName: string;
  Pair: TJSONPair;
function CreateJSONValueForVariant(const aValue: Variant): TJSONValue;

begin
  case VarType(aValue) of
    varInteger:
      Result := TJSONNumber.Create(Integer(aValue)); // 直接为整数创建TJSONNumber
    varSingle, varDouble:
      Result := TJSONNumber.Create(Double(aValue)); // 对于单精度和双精度浮点数,直接传入Value
    varString:
      Result := TJSONString.Create(string(aValue));
    varBoolean:
      Result := TJSONBool.Create(aValue);
    else
       raise Exception.CreateFmt('Unsupported variant type encountered: %s', [VarToStr(aValue)]); // 更详细的错误信息

  end;
end;

begin
  CurrentObject := JsonObject;
  for I := Low(FieldNames) to High(FieldNames) - 1 do
  begin
    FieldName := FieldNames[I];
    if not CurrentObject.TryGetValue(FieldName, CurrentObject) or not (CurrentObject is TJSONObject) then
    begin
      // 如果路径段不存在或不是对象,则创建一个新的对象
      CurrentObject.AddPair(FieldName, TJSONObject.Create);
      CurrentObject := CurrentObject.Values[FieldName] as TJSONObject;
    end
    else
    begin
      // 继续深入到下一个路径段
     // CurrentObject := CurrentObject.Values[FieldName] as TJSONObject;

      if CurrentObject.Values[FieldName] is TJSONObject then
      begin
        CurrentObject := CurrentObject.Values[FieldName] as TJSONObject;
      end
      else
      begin
        // 如果不是对象,则不应该继续遍历,直接跳出循环
        Break;
      end;


    end;
  end;


  // 到达最后一级路径,设置值
  if Assigned(CurrentObject) then
  begin
    FieldName  := FieldNames[High(FieldNames)];
    Pair := CurrentObject.Get(FieldName);
    if Pair = nil then
      CurrentObject.AddPair(FieldName, CreateJSONValueForVariant(NewValue)) // 自动根据NewValue类型创建JSONValue
    else
      Pair.JsonValue := CreateJSONValueForVariant(NewValue);

    end;

  Result := JsonObject;
end;
调用:

  var JsonObject : TJSONObject;
  JsonObject := TJSONObject.ParseJSONValue('{}') as TJSONObject;
  JsonObject :=TSQLHelp.UpdateNestedJSONField(JsonObject, ['person', 'age'], Integer(30));//注意这里,否则不识别导致异常
  ShowMessage(JsonObject.ToString);

根据path:['person', 'age']检查json,有就更新,没有就创建。是否非常方便!

 

 json有值,就修改:

  var JsonObject : TJSONObject;
  JsonObject := TJSONObject.ParseJSONValue('{"person":{"name":"John","age":90,"address":{"city":"New York","country":"USA"}}}') as TJSONObject;
  JsonObject :=TSQLHelp.UpdateNestedJSONField(JsonObject, ['person', 'age'], Integer(30));
  ShowMessage(JsonObject.ToString);

  var JsonObject : TJSONObject;
  JsonObject := TJSONObject.ParseJSONValue('{"person":{"name":"John","age":90,"address":{"city":"New York","country":"USA"}}}') as TJSONObject;
  JsonObject :=TSQLHelp.UpdateNestedJSONField(JsonObject, ['person', 'age'], Integer(30));
  JsonObject :=TSQLHelp.UpdateNestedJSONField(JsonObject, ['接触暴露', '皮肤','破损'], True);
  ShowMessage(JsonObject.ToString);

 

 

 have fun

posted on 2024-06-03 11:39  USEGEAR  阅读(18)  评论(0编辑  收藏  举报