thriftpy2 icon indicating copy to clipboard operation
thriftpy2 copied to clipboard

how to convert thrift to dict with map

Open yexiaoya opened this issue 4 years ago • 4 comments

thrift

struct WordCloudParam { 1: optional map<string, i32> word_counts # {'a': 10, 'b': 20} }

import thriftpy2.protocol.json as thrift_json

param_obj = WordCloudParam(word_counts={'a': 10, 'b': 20}) param_json = thrift_json.struct_to_json(param_obj)

it return => {'word_counts': [{'value': 10, 'key': u'a'}, {'value': 20, 'key': u'b'}]} but i expect as: {'a': 10, 'b': 20}

yexiaoya avatar Apr 26 '21 12:04 yexiaoya

I test this repos. https://github.com/wayhome/thrift_json/tree/master/thrift_json it seems ok, to convert obj with map to json.

yexiaoya avatar Apr 26 '21 13:04 yexiaoya

    elif ttype == TType.MAP:
        (key_ttype, key_ttype_info, val_ttype, val_ttype_info) = ttype_info
        ret = dict([(self._convert(k, key_ttype, key_ttype_info),
                     self._convert(v, val_ttype, val_ttype_info)) for (k, v) in val.items()])

yexiaoya avatar Apr 26 '21 13:04 yexiaoya

how about change this func? return a dict

def map_to_json(val, spec):
    res = dict()
    if isinstance(spec[0], int):
        key_type = spec[0]
        key_spec = None
    else:
        key_type, key_spec = spec[0]

    if isinstance(spec[1], int):
        value_type = spec[1]
        value_spec = None
    else:
        value_type, value_spec = spec[1]

    for k, v in val.items():
        if json_value(key_type, k, key_spec):
            res[json_value(key_type, k, key_spec)] = json_value(value_type, v, value_spec)

    return res

yexiaoya avatar Apr 26 '21 14:04 yexiaoya

@yexiaoya Try this function: https://github.com/Thriftpy/thriftpy2/issues/152#issuecomment-768023281

JonnoFTW avatar May 20 '21 01:05 JonnoFTW