简体   繁体   中英

Convert JSON multi-dimensional array into single-dimensional array in Python

I have a JSON file that goes along the lines of:

{
    "pathID": 1,
    "preText": "Please select based on the options.",
    "selection": "",
    "options": 
        {
            "pathID": 2,
            "preText": "This is Option 1",
            "selection": ""
        }
}

Which I would like to convert to 1-dimensional, which would look similar to:

{
    "pathID": 1,
    "preText": "Please select based on the options.",
    "selection": ""
},
{
    "pathID": 2,
    "preText": "This is Option 1",
    "selection": ""
}

How would I go about this in Python? I've tried stuff like np.asarray and using chain maps.

I'm very new to Python and working with JSON files (both my first day).

Assuming here that you want your output dictionaries to be stored in a list, you could do:

data_in = {
    "pathID": 1,
    "preText": "Please select based on the options.",
    "selection": "",
    "options": 
        {
            "pathID": 2,
            "preText": "This is Option 1",
            "selection": ""
        }
}

# start with a 1-element list which just contains a copy of the input 
data_out = [data_in.copy()]

# but go through the items of the dictionary, and if any values are themselves
# dictionaries then remove them from this dictionary, and add them to the output 
# list
for k, v in data_in.items():
    if isinstance(v, dict):
        del data_out[0][k]
        data_out.append(v)

print(data_out)

This gives essentially this, although pretty-printed here for readability:

[
    {
        'pathID': 1,
        'preText': 'Please select based on the options.',
        'selection': ''
    },
    {
        'pathID': 2,
        'preText': 'This is Option 1',
        'selection': ''
    }
]

(In a JSON dump this would use double-quotes but otherwise look the same.)

You could give the python module FlatDict a try.

flatdict is a Python module for interacting with nested dicts as a single level dict with delimited keys. flatdict supports Python 3.5+.

This might be better than creating your custom solution

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM