File: util.py

package info (click to toggle)
chargebee-python 1.6.6-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 484 kB
  • sloc: python: 1,008; makefile: 6; sh: 3
file content (41 lines) | stat: -rw-r--r-- 1,272 bytes parent folder | download | duplicates (2)
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
from chargebee import compat

def serialize(value, prefix=None, idx=None):

    serialized = {}

    if isinstance(value, dict):
        for k, v in list(value.items()):
            if isinstance(v, (dict, list, tuple)):
                serialized.update(serialize(v, k))
            else:
                key = ''.join([
                    prefix or '',
                    '[%s]' % k if prefix is not None else k,
                    '[%s]' % idx if idx is not None else '',
                ])
                serialized.update({key: get_val(v)})

    elif isinstance(value, (list, tuple)):
        for i, v in enumerate(value):
            serialized.update(serialize(v, prefix, i))

    else:
        if prefix is not None and idx is not None:
            key = prefix + '[' + str(idx) +']'
            serialized.update({key: get_val(value)})
        else:
            raise TypeError("only hash or arrays are allowed as value")

    return serialized

def get_val(val):
    if val is None:
        return ''
    elif isinstance(val, bool):
        return str(val).lower()
    else:
        if compat.py_major_v < 3 and isinstance(val, unicode): 
              return val.encode("utf-8")
        else:
           return val;