如何在ada中访问JSON数组的特定位置?

时间:2019-07-09 08:55:31

标签: arrays json ada

我有一个像这样的数组:

{
   "Test":
         [
            0,
            1,
            2,
            3,
            4
         ]
}

我正在使用GNATCOLL.JSON,但没有看到任何函数来处理数组并执行类似的操作,例如:

integer = Test (2);

1 个答案:

答案 0 :(得分:5)

您可能想尝试:

function Get (Val : JSON_Value; Field : UTF8_String) return JSON_Array

然后

function Get (Arr : JSON_Array; Index : Positive) return JSON_Value

然后

function Get (Val : JSON_Value; Field : UTF8_String) return Integer

作为示例,运行程序:

main.adb

with Ada.Text_IO;              
with Ada.Text_IO.Unbounded_IO;
with Ada.Strings.Unbounded;

with GNATCOLL.JSON;                 

procedure Main is

   use Ada.Text_IO;
   use Ada.Strings.Unbounded;

   Input : Unbounded_String := Null_Unbounded_String;   

begin


   --  Read.
   declare
      use Ada.Text_IO.Unbounded_IO;    
      Fd : File_Type;
   begin  
      Open (Fd, In_File, "./example.json");
      while not End_Of_File (Fd) loop
         Input := Input & Unbounded_String'(Get_Line (Fd));
      end loop;
      Close (fd);
   end;


   --  Process.
   declare         
      use GNATCOLL.JSON;     
      Root : JSON_Value := Read (Input);
      Test : JSON_Array := Root.Get ("Test");
   begin    
      for I in 1 .. Length (Test) loop
         Put_Line ("Array element :" & Integer'Image (Get (Test, I).Get));
      end loop;     
   end;     

end Main;

使用

example.json

{
   "Test":
         [
            0,
            1,
            2,
            3,
            4
         ]
}

收益

$ ./main
Array element : 0
Array element : 1
Array element : 2
Array element : 3
Array element : 4