Python需要将花括号替换为(花括号和逗号)

2024-09-29 17:17:49 发布

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

我有一个包含数十万行的JSON响应,所有的解析都来自python字典,并使用JSON.load转换为JSON

现在获取带有无效响应的JSON响应,因此解决方法如下

响应

{
    "ComplianceType": "",
    "Details": {
        "InstalledTime": "",
        "PatchBaselineId": "",
        "PatchState": ""
    },
    "ExecutionSummary": {
        "ExecutionId": "",
        "ExecutionTime": "",
        "ExecutionType": ""
    },
    "Id": "",
    "ResourceId": "",
    "ResourceType": "",
    "Severity": "",
    "Status": "",
    "Title": ""
}
{
    "ComplianceType": "",
    "Details": {
        "InstalledTime": "",
        "PatchBaselineId": "",
        "PatchState": ""
    },
    "ExecutionSummary": {
        "ExecutionId": "",
        "ExecutionTime": "",
        "ExecutionType": ""
    },
    "Id": "",
    "ResourceId": "",
    "ResourceType": "",
    "Severity": "",
    "Status": "",
    "Title": ""
}

设法使其有效

[{
    "ComplianceType": "",
    "Details": {
        "InstalledTime": "",
        "PatchBaselineId": "",
        "PatchState": ""
    },
    "ExecutionSummary": {
        "ExecutionId": "",
        "ExecutionTime": "",
        "ExecutionType": ""
    },
    "Id": "",
    "ResourceId": "",
    "ResourceType": "",
    "Severity": "",
    "Status": "",
    "Title": ""
},
{
    "ComplianceType": "",
    "Details": {
        "InstalledTime": "",
        "PatchBaselineId": "",
        "PatchState": ""
    },
    "ExecutionSummary": {
        "ExecutionId": "",
        "ExecutionTime": "",
        "ExecutionType": ""
    },
    "Id": "",
    "ResourceId": "",
    "ResourceType": "",
    "Severity": "",
    "Status": "",
    "Title": ""
}
]

当我尝试使用sed shell时,我需要通过程序执行这些操作-->#sed-i的#}、#test.json<;--。此shell命令替换},in},并返回为}

[{
    "ComplianceType": "",
    "Details": {
        "InstalledTime": "",
        "PatchBaselineId": "",
        "PatchState": ""
    },,
    "ExecutionSummary": {
        "ExecutionId": "",
        "ExecutionTime": "",
        "ExecutionType": ""
    },,
    "Id": "",
    "ResourceId": "",
    "ResourceType": "",
    "Severity": "",
    "Status": "",
    "Title": ""
},
{
    "ComplianceType": "",
    "Details": {
        "InstalledTime": "",
        "PatchBaselineId": "",
        "PatchState": ""
    },,
    "ExecutionSummary": {
        "ExecutionId": "",
        "ExecutionTime": "",
        "ExecutionType": ""
    },,
    "Id": "",
    "ResourceId": "",
    "ResourceType": "",
    "Severity": "",
    "Status": "",
    "Title": ""
},
]

请提供一个适用于shell或python的解决方案


Tags: idtitlestatusdetailsexecutiontimeseverityresourceidresourcetype
1条回答
网友
1楼 · 发布于 2024-09-29 17:17:49

根据您的示例输入,这可能适用于您:

$ cat input.json \
    | grep -v -e '^[[:space:]]*$' \
    | sed -e '1s/^/[/'   \
          -e '$s/$/]/'   \
          -e 's/^}$/},/'
  • grep删除任何空行(如果存在)。这很重要,因为下面的sed需要在最后一个非空行上操作
  • 第一个sed表达式将[添加到第一行的开头
  • 第二个sed表达式将]添加到最后一行的末尾
  • 最后的sed表达式在一行中的任何}后面添加一个逗号

通过在第三个sed之前应用第二个},最后一个}变为}],因此}不再单独在一行上

相关问题 更多 >

    热门问题