How to convert Python dict to JSON as a list, if possible

I am trying to serialize Python objects to JSON using json.dumps. If you serialize dictwith json.dumps, it will obviously be serialized as a JSON dictionary {..}; if you serialize listor tuple, it will be a JSON array.

I want to know if there is a way to easily serialize Python dictas JSON list, if possible. If possible, I mean if the keys start at 0 and are ordered, for example:

{0:'data',1:'data',2:'data}

The above will be serialized in JSON as: '{"0": "data", "1": "data", "2": "data"}'but I would like it to be serialized as ['data','data','data'], since the keys start at 0 and are ordered.

My reasoning is that I have a lot of JSON data that is serialized from PHP, where there are keys in PHP arrays, and if the keys are sequenced as described above, PHP json.encodeuses arrays if they are entered in any other ways, they are serialized like dictionaries JSON I want my JSON serializations to match both my PHP and Python code. Unfortunately, changing PHP code is not an option in my case.

Any suggestions? The only solution I found was to write my own function to go through and check each python dictionary and see if it can be converted to listbefore first json.dumps.

EDIT . This object that I am serializing can be listor dict, it can also have additional dict inside, lists, etc. (nesting). I am wondering if there is any “simple” way to do this, otherwise I believe that I can write a recursive solution myself. But it is always better to use existing code to avoid errors.

+5
source share
3 answers

I don’t know a solution without recursion ... Although you can call your converter from encodeyour custom method Encoder, it will just add unnecessary complexity.

In [1]: import json

In [2]: d = {"0": "data0", "1": "data1", "2": {"0": "data0", "1": "data1", "2": "data2"}}

In [3]: def convert(obj):
   ...:     if isinstance(obj, (list, tuple)):
   ...:         return [convert(i) for i in obj]
   ...:     elif isinstance(obj, dict):
   ...:         _, values = zip(*sorted(obj.items()))  
   ...:         return convert(values)
   ...:     return obj

In [4]: json.dumps(convert(d))
Out[4]: '["data0", "data1", ["data0", "data1", "data2"]]'
+3
source

, , , :

items = sorted(d.items(), key=lambda item: item[0])
values = [item[1] for item in items]
json_dict = json.dumps(values)
+2

json.JSONEncoder, JSON-, .

dictlist ( , ), dict list, JSONEncoder.default, JSON-.

, JSON dict , , dict list dict.

:

def convert_to_list(obj):
    obj_list = []
    for i in range(len(obj)):
        if i not in obj:
            return obj  # Return original dict if not an ordered list
        obj_list.append(obj[i])
    return obj_list
+1

All Articles