Convert python dict to Json

前端 未结 1 561
梦谈多话
梦谈多话 2021-01-23 22:07

I\'m getting the following dict from a method:

{\'patterns\': {(38,): 2, (19,): 4, (9, 19): 3, (9,): 4}, 
  \'rules\': {(9,): ((19,), 0.75), (19,): ((9,), 0.75)}         


        
1条回答
  •  被撕碎了的回忆
    2021-01-23 22:26

    json only supports string as key, so tuple-as-key isn't allowed

    As @SingleNegationElimination said in his answer of a similar question:

    You can't serialize that as json, json has a much less flexible idea about what counts as a dict key than python.

    However, with a little custom extension of @SingleNegationElimination's remap_keys function, you could convert your invalid dict to a valid json object.

    def remap_keys(d):
        if not isinstance(d, dict):
            return d
        rslt = []
        for k, v in d.items():
            k = remap_keys(k)
            v = remap_keys(v)
            rslt.append({'key': k, 'value': v})
        return rslt
    
    >>> remap_keys(myDict)
    [{'key': 'patterns',
      'value': [{'key': (38,), 'value': 2},
                {'key': (19,), 'value': 4},
                {'key': (9, 19), 'value': 3},
                {'key': (9,), 'value': 4}]},
     {'key': 'rules',
      'value': [{'key': (9,), 'value': ((19,), 0.75)},
                {'key': (19,), 'value': ((9,), 0.75)}]}]
    

    And you could succesfully json.dumps your dict by:

    json.dumps(remap_keys(myDict))
    

    0 讨论(0)
提交回复
热议问题