【问题标题】:Convert JSON multi-dimensional array into single-dimensional array in Python在Python中将JSON多维数组转换为一维数组
【发布时间】:2020-11-19 00:28:48
【问题描述】:

我有一个 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 文件(都是我的第一天)。

【问题讨论】:

  • 这是完整的结构吗?然后只有一个外循环和一个内循环。 r = []; for x in f: r.append(x); opt = x.get('options', []); for y in opt: r.append(y)
  • 您的输出不是有效的 JSON。您是否打算将这些字典放在一个列表中?
  • 从您的示例 JSON 看起来,您希望从对象和选项属性创建一个列表。正确的?还有一件事,你能再举一个 JSON 数据的例子吗?

标签: python arrays json multidimensional-array


【解决方案1】:

假设您希望将输出字典存储在列表中,您可以这样做:

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 转储中,这将使用双引号,但其他方面看起来相同。)

【讨论】:

    【解决方案2】:

    你可以试试python模块FlatDict

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

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

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 2019-06-29
      • 1970-01-01
      • 1970-01-01
      • 2015-01-06
      相关资源
      最近更新 更多