dictionary.a68

     
   1  COMMENT
   2  
   3  @section Synopsis
   4  
   5  Write Python-style dictionaries in json format.
   6  
   7  COMMENT
   8  
   9  MODE DICT = FLEX [0] PAIR,
  10       PAIR = STRUCT (KEY key, VALUE val),
  11       VALUE = UNION (BASIC, [] BASIC, REF DICT, VOID),
  12       BASIC = UNION (INT, REAL, BOOL, STRING),
  13       KEY = STRING;
  14  
  15  REF DICT empty dict = NIL, VALUE null = EMPTY;
  16  
  17  DICT empty := PAIR ("empty_field", null);
  18  
  19  CHAR quote = """";
  20  
  21  OP JSON = (REF DICT dict) VOID:
  22  
  23     # Write dictionary in json format. #
  24  
  25     IF dict IS empty dict
  26     THEN ~
  27     ELSE print ("{");
  28          
  29          FOR i TO UPB dict
  30          DO OP ONE = (VALUE v) VOID:
  31                CASE v
  32                IN (VOID): print ("null"),
  33                   (REF DICT d): JSON d,
  34                   (BASIC w):
  35                      CASE w
  36                      IN (STRING s): print (quote + s + quote),
  37                         (BOOL b): print ((b | "True" | "False")),
  38                         (INT i): print (whole (i, 0)),
  39                         (REAL r): print (stringf (HEAP STRING, ($%g$, r)))
  40                      ESAC,
  41                   ([] BASIC a): (
  42                      print ("{");
  43                      FOR j TO UPB a
  44                      DO ONE (a[j]);
  45                         print((j < UPB a | ", " | "}"))
  46                      OD
  47                   )
  48                ESAC;
  49  
  50             print ((quote, key OF dict[i], quote, ": "));
  51             ONE val OF dict[i];
  52             print ((i < UPB dict | ", " | "}"))
  53          OD
  54     FI;
  55  
  56  [] BASIC row = (1, pi, TRUE, "algol 68");
  57  DICT test := (("empty_dict", empty), ("row", row), ("string", "string"));
  58  
  59  JSON test;
  60  
  61  newline (standout)
     


© 2002-2024 J.M. van der Veer (jmvdveer@xs4all.nl)