summaryrefslogtreecommitdiff
path: root/lib/data_parameters.py
blob: 8f1fbb06f39fb41d449a0942215a1aee88dc9b47 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
Utilities for parameter extraction from data layout.

Parameters include the amount of keys, length of strings (both keys and values),
length of lists, ane more.
"""

def _string_value_length(json):
    if type(json) == str:
        return len(json)

    if type(json) == dict:
        return sum(map(_string_value_length, json.values()))

    if type(json) == list:
        return sum(map(_string_value_length, json))

    return 0

def _string_key_length(json):
    if type(json) == dict:
        return sum(map(len, json.keys())) + sum(map(_string_key_length, json.values()))

    return 0

def _num_keys(json):
    if type(json) == dict:
        return len(json.keys()) + sum(map(_num_keys, json.values()))

    return 0

def _num_objects(json):
    if type(json) == dict:
        return 1 + sum(map(_num_objects, json.values()))

    return 0

def json_to_param(json):
    """Return numeric parameters describing the structure of JSON data."""

    ret = dict()

    ret['strlen_keys'] = _string_key_length(json)
    ret['strlen_values'] = _string_value_length(json)
    ret['num_keys'] = _num_keys(json)
    ret['num_objects'] = _num_objects(json)

    return ret