在Python中将JSON多维数组转换为一维数组

2024-06-16 12:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个JSON文件,大致如下:

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

我想将其转换为一维,看起来类似于:

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

我将如何在Python中实现这一点? 我尝试过像np.asarray和使用链映射之类的东西

我对Python和JSON文件非常陌生(都是第一天)


Tags: 文件thejsonisonnpthisselect
2条回答

假设您希望输出词典存储在列表中,您可以执行以下操作:

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)

这从本质上讲是这样的,尽管为了便于阅读,这里打印得很漂亮:

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

(在JSON转储中,这将使用双引号,但在其他方面看起来相同。)

您可以尝试一下python模块FlatDict

flatdict是一个Python模块,用于作为带分隔键的单级dict与嵌套dict交互。flatdict支持Python 3.5+

这可能比创建自定义解决方案要好

相关问题 更多 >