Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

51
LINES

< > BotCompany Repo | #1032561 // JSONKeyTree

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (5666L/32K).

1  
// data = output of jsonDecode()
2  
sclass JSONKeyTree {
3  
  new TreeSet<S> out;
4  
  new MultiMap<S, O> examples;
5  
  new Map<S, IntRange> listSizes;
6  
  
7  
  S render(O data) {
8  
    process(data);
9  
    ret lines(out, key -> {
10  
      var xmpls = examples.get(key);
11  
      var ls = listSizes.get(key);
12  
      if (ls != null)
13  
        if (l(ls) == 0)
14  
          ret key + " with " + nElements(ls.start);
15  
        else
16  
          ret key + " with between " + ls.start + " and " + ls.end + " elements";
17  
      else if (nempty(xmpls))
18  
        ret key + " = e.g. " + jsonEncode(first(xmpls));
19  
      else
20  
        ret key;
21  
    });
22  
  }
23  
  
24  
  Set<S> get(O data) {
25  
    process(data);
26  
    ret out;
27  
  }
28  
  
29  
  void process(S prefix default "", O data) {
30  
    if (data cast L) {
31  
      S l = prefix + " is a list";
32  
      out.add(l);
33  
      listSizes.put(l, joinIntRanges(listSizes.get(l), emptyIntRange(l(data))));
34  
      S s = prefix + "[]";
35  
      for (O o : data)
36  
        process(s, o);
37  
    } else if (data cast Map) {
38  
      out.add(prefix + " is a map");
39  
      for (O key, O val : castMapToMapO(data)) {
40  
        S s = addDotIfNempty(prefix) + key;
41  
        out.add(s);
42  
        process(s, val);
43  
      }
44  
    } else if (data == null)
45  
      out.add(prefix + " is null");
46  
    else {
47  
      out.add(prefix + " is a " + shortClassName(data));
48  
      examples.put(prefix, data);
49  
    }
50  
  }
51  
}

download  show line numbers  debug dex  old transpilations   

Travelled to 3 computer(s): bhatertpkbcr, mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1032561
Snippet name: JSONKeyTree
Eternal ID of this version: #1032561/15
Text MD5: 65d9005c136ac2defe9d298ad9958a0f
Transpilation MD5: fce5c573b3a934174a7f3ff1056ac1d7
Author: stefan
Category: javax / json
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-09-23 00:20:11
Source code size: 1388 bytes / 51 lines
Pitched / IR pitched: No / No
Views / Downloads: 194 / 360
Version history: 14 change(s)
Referenced in: [show references]