首页 > 其他分享 >mormot2 IDocList&IDocDict

mormot2 IDocList&IDocDict

时间:2024-07-18 18:56:15浏览次数:12  
标签:20 list two assert dict IDocList mormot2 IDocDict

mormot2 IDocList&IDocDict

uses mormot.core.variants

mormot2模仿Python Lists and Dictionaries JSON操作,封装了IDocList&IDocDict俩个新的接口。

IDocList (别名IDocArray) 存储a list of elements;

IDocDict (别名IDocObject) 存储a dictionary of key:value pairs.

例程一

var
  list: IDocList;
  dict: IDocDict;
  v: variant;
  i: integer;
begin  
  // creating a new list/array from items
  list := DocList([1, 2, 3, 'four', 1.0594631]); // double are allowed by default

  // iterating over the list
  for v in list do
    Listbox1.Items.Add(v); // convert from variant to string

  // or a sub-range of the list (with Python-like negative indexes)
  for i in list.Range(0, -3) do
    Listbox2.Items.Add(IntToStr(i)); // [1, 2] as integer

  // search for the existence of some elements
  assert(list.Exists(2));
  assert(list.Exists('four'));

  // a list of objects, from JSON, with an intruder
  list := DocList('[{"a":0,"b":20},{"a":1,"b":21},"to be ignored",{"a":2,"b":22}]');

  // enumerate all objects/dictionaries, ignoring non-objects elements
  for dict in list.Objects do
  begin
    if dict.Exists('b') then
      ListBox2.Items.Add(dict['b']);
    if dict.Get('a', i) then
      ListBox3.Items.Add(IntToStr(i));
  end;

  // delete one element
  list.Del(1);
  assert(list.Json = '[{"a":0,"b":20},"to be ignored",{"a":2,"b":22}]');

  // extract one element
  if list.PopItem(v, 1) then
    assert(v = 'to be ignored');

  // convert to a JSON string
  Label1.Caption := list.ToString;
  // display '[{"a":0,"b":20},{"a":2,"b":22}]'
end;

例程二:

var
  v: variant;
  f: TDocDictFields;
  list, list2: IDocList;
  dict: IDocDict;
begin
  list := DocList('[{"a":10,"b":20},{"a":1,"b":21},{"a":11,"b":20}]');

  // sort a list/array by the nested objects field(s)
  list.SortByKeyValue(['b', 'a']);
  assert(list.Json = '[{"a":10,"b":20},{"a":11,"b":20},{"a":1,"b":21}]');
  
  // enumerate a list/array with a conditional expression 
  for dict in list.Objects('b<21') do
    assert(dict.I['b'] < 21);

  // another enumeration with a variable as conditional expression
  for dict in list.Objects('a=', 10) do
    assert(dict.I['a'] = 10);

  // create a new IDocList from a conditional expression
  list2 := list.Filter('b =', 20);
  assert(list2.Json = '[{"a":10,"b":20},{"a":11,"b":20}]');

  // direct access to the internal TDocVariantData storage
  assert(list.Value^.Count = 3);
  assert(list.Value^.Kind = dvArray);
  assert(dict.Value^.Kind = dvObject);
 
  // TDocVariantData from a variant intermediary
  v := list.AsVariant;
  assert(_Safe(v)^.Count = 3);
  v := dict.AsVariant;
  assert(_Safe(v)^.Count = 2);

  // high-level Python-like methods
  if list.Len > 0 then
    while list.PopItem(v) do
    begin
      assert(list.Count(v) = 0); // count the number of appearances
      assert(not list.Exists(v));
      Listbox1.Items.Add(v.a); // late binding 
      dict := DocDictFrom(v); // transtyping from variant to IDocDict
      assert(dict.Exists('a') and dict.Exists('b'));
      // enumerate the key:value elements of this dictionary
      for f in dict do
      begin
        Listbox2.Items.Add(f.Key);
        Listbox3.Items.Add(f.Value);
      end;
    end;

  // create from any complex "compact" JSON
  // (note the key names are not "quoted")
  list := DocList('[{ab:1,cd:{ef:"two"}}]');

  // we still have the late binding magic working
  assert(list[0].ab = 1);
  assert(list[0].cd.ef = 'two');

  // create a dictionary from key:value pairs supplied from code
  dict := DocDict(['one', 1, 'two', 2, 'three', _Arr([5, 6, 7, 'huit'])]);
  assert(dict.Len = 3); // one dictionary with 3 elements
  assert(dict.Json = '{"one":1,"two":2,"three":[5,6,7,"huit"]}');

  // convert to JSON with nice formatting (line feeds and spaces)
  Memo1.Caption := dic.ToString(jsonHumanReadable);

  // sort by key names
  dict.Sort;
  assert(dict.Json = '{"one":1,"three":[5,6,7,"huit"],"two":2}');

  // note that it will ensure faster O(log(n)) key lookup after Sort:
  // (beneficial for performance on objects with a high number of keys)
  assert(dict['two'] = 2); // default lookup as variant value
  assert(dict.I['two'] = 2); // explicit conversion to integer
end;

 

标签:20,list,two,assert,dict,IDocList,mormot2,IDocDict
From: https://www.cnblogs.com/hnxxcxg/p/18310253

相关文章

  • mormot2路由
    mormot2路由unitmvc.Controller.Api;interfaceusessystem.SysUtils,system.StrUtils,system.Classes,mormot.core.base,mormot.core.os,mormot.core.rtti,mormot.core.log,mormot.core.text,mormot.net.sock,mormot.net.http,mormot.ne......
  • mORMot2 的 mormot.defines.inc
    mORMot2的mormot.defines.inc到底配置了啥,居然写了700多行!{这个文件是开源SynopsemORMot框架2的一部分,遵循MPL/GPL/LGPL三重许可协议-详见LICENSE.md定义了一组集中的条件编译指令,包含在所有框架单元中,也可以用于您自己的私有单元。}(********************......
  • IDocList/IDocDict JSON for Delphi and FPC
    IDocList/IDocDictJSONforDelphiandFPC【英文原文】多年来,我们的开源mORMot框架提供了多种方式,以处理在运行时定义的任何数组/对象文档组合,例如通过JSON,它具备许多功能,并且非常高的性能。我们的TDocVariant自定义变体类型是处理这类无模式数据的一种强大方式,但一些用户......
  • mORMot2 获取数据集(泛型)
    mORMot2获取数据集(泛型)第14章使用泛型现代Delphi版本的一个特点是能够使用泛型。varaMale:TSQLBaby;BeginaMale:=TSQLBaby.CreateAndFillPrepare(Client,'NameLIKE?ANDSex=?',['A\%',ord(sMale)]);trywhileaMale.FillOnedoDoSomethingWith(aM......
  • mORMot2 获取数据集
    mORMot2获取数据集其实在前面想学习mORMot1部分已经收集了很多关于CRUD的示例了,但感觉总是不通透,不能很好使用,一则mORMot函数命令规则比较不同寻常,另外确实示例太少,其实代码注释倒是讲了很多。procedureFillPrepare(Table:TOrmTable;aCheckTableName:TOrmCheckTableName=......
  • mORMot2 定义多对多关系
    mORMot2定义多对多关系处理“hasmany”和“hasmanythrough”关系时,主要涉及到的是多对多关系的数据库设计和管理。以下是对您提供的文本的技术性翻译和解释:多对多关系是通过一个专门为这种关系创建的表来追踪的,将这个关系转变为两个指向相反方向的一对多关系。默认情况下,......
  • mormot2 json 操作
    [mormot2json操作]本文非完全原创,本文部分内容来自博客园,作者:{咏南中间件}unitmormot2.json.serial;interfaceusesClasses,SysUtils,mormot.core.buffers,mormot.core.text,mormot.core.json,mormot.core.base//;type{TSerial}TSerial......
  • mORMot2 的 Logger日志
    mORMot2的Logger日志Logger很多框架都有,简单的实现就是一个队列加一根线,有复杂的,QDAC里面涉及的就很巧妙,本来QDAC就是个线程框架,所以也有先天优势。在mORMot里面自然也有日志实现,它设计的比较麻烦。mORMot的Logger初始化beginTSynLog.Family.Level:=LOG_VERBOSE;......
  • mormot2 笔记(四) Services的使用
    constructorTMyRestServer.Create(Port:Word);begininheritedCreate;FRestServerDB:=TRestServerDB.Create(TOrmModelFactory.ModelInstance,SQLITE_MEMORY_DATABASE_NAME);FRestServerDB.DB.Synchronous:=smOff;FRestServerDB.DB.LockingMode:=lmExc......
  • mormot2 笔记(三) 实体转JSON
    TOL=class(TObject)publicprocedureW(W:TJsonWriter;Instance:TObject;Options:TTextWriterWriteObjectOptions);end;TPerson=classprivateFName:string;FID:integer;FSex:Byte;publishedpropertyID:integerread......