Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to convert thrift to dict with map #171

Open
yexiaoya opened this issue Apr 26, 2021 · 4 comments
Open

how to convert thrift to dict with map #171

yexiaoya opened this issue Apr 26, 2021 · 4 comments
Labels
question Further information is requested

Comments

@yexiaoya
Copy link

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
Copy link
Author

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
Copy link
Author

    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
Copy link
Author

yexiaoya commented Apr 26, 2021

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

@JonnoFTW
Copy link
Contributor

@yexiaoya Try this function: #152 (comment)

@aisk aisk added the question Further information is requested label Apr 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

3 participants