Statistics
| Branch: | Tag: | Revision:

root / commissioning / utils / clijson.py @ a2db0eb5

History | View | Annotate | Download (1.8 kB)

1
#!/usr/bin/env python
2

    
3
import re
4

    
5
keywords = set(['true', 'false', 'null'])
6
unquoted = set('{}[]"\'0123456789')
7
name_matcher = re.compile('^[\w @_.+-]+$', re.UNICODE)
8

    
9
def is_name(token):
10
    if name_matcher.match(token):
11
        return 1
12
    return 0
13

    
14
def quote(token, is_dict):
15
    if not token:
16
        return '""'
17

    
18
    if not is_name(token[0]):
19
        comma = ', ' if token[-1] not in '{[' else ''
20
        return token + comma
21

    
22
    k, sep, v = token.partition('=')
23
    if not sep or not v.strip('='):
24
        k, sep, v = token.partition(':')
25

    
26
    if not sep:
27
        if is_name(token) and token not in keywords:
28
            token = '"' + token + '"'
29

    
30
        comma = ', ' if token[-1] not in '{[' else ''
31
        return token + comma
32

    
33
    k = '"' + k + '"'
34
    is_dict.add(1)
35

    
36
    if not v:
37
        v = '""'
38
    else:
39
        if v.isalnum() and not v.isdigit() and v not in keywords:
40
            v = '"' + v + '"'
41

    
42
    comma = ', ' if v[-1] not in '{[' else ''
43
    return k + ':' + v + comma
44

    
45

    
46
def clijson(argv):
47
    tokens = argv
48
    is_dict = set()
49

    
50
    strlist = []
51
    append = strlist.append
52
    dictionary = 0
53
    token_join = None
54

    
55
    for t in tokens:
56
        t = t.strip()
57

    
58
        if strlist and t and t in '}]':
59
            strlist[-1] = strlist[-1].rstrip(', ')
60

    
61
        if token_join:
62
            t = token_join + t
63
            token_join = None
64
        elif t.endswith(':'):
65
            token_join = t
66
            continue
67

    
68
        t = quote(t, is_dict)
69
        append(t)
70

    
71
    if not strlist:
72
        return 'null'
73

    
74
    if strlist[0][0] not in '{[':
75
        strlist[-1] = strlist[-1].rstrip(', ')
76
        o, e = '{}' if is_dict else '[]'
77
        strlist = [o] + strlist + [e]
78

    
79
    if strlist[-1][-1] in ']}':
80
        strlist[-1] = strlist[-1].rstrip(',')
81
    return ''.join(strlist)
82

    
83

    
84
if __name__ == '__main__':
85
    from sys import argv
86

    
87
    print clijson(argv[1:])
88