Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access a specific position of a JSON array in ada?

Tags:

json

arrays

ada

I have an array like this:

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

I'm using GNATCOLL.JSON but I don't see any function to handle arrays and do something like this, for example:

integer = Test (2);
like image 546
Yorch Avatar asked Jul 09 '19 08:07

Yorch


1 Answers

You might want to try:

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

and then

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

and then

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

As an example, running the program:

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;

with

example.json

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

yields

$ ./main
Array element : 0
Array element : 1
Array element : 2
Array element : 3
Array element : 4
like image 132
DeeDee Avatar answered Nov 15 '22 01:11

DeeDee