使用 sed 压缩 JSON 数组

使用 sed 压缩 JSON 数组

我有一个以下格式的 JSON 输出:

{
  "DaysCfg": {
    "Range": {
      "lowerDate": "2017-07-28T00:00:00.000-04:00",
      "upperDate": "2017-08-04T00:00:00.000-04:00"
    },
    "DaysInPeriod": 8,
    "DaysToSchedule": [
      0,
      1,
      2,
      3,
      4,
      5,
      6
    ]
  },
  "DepartmentsID": [
    138837,
    139734,
    141934,
    142436,
    149687,
    151049
  ],
  "EmployeesID": [
    5039,
    5170,
    5889,
    6051,
    6236,
    7208,
    7281,
    8776,
    8781,
    8936,
    9261
  ],
  "EndDate": "2017-08-03T23:59:00.000-04:00",
  "IntervalSize": 15,
  "IsActivitiesEnabled": true,
  "ModifyExisting": false,
  "OrignId": 134721,
  "PrimaryOption": 0,
  "SchoolDays": [],
  "ScChanges": [],
  "StartDate": "2017-07-28T00:00:00.000-04:00",
  "ZonesToSchedule": [
    5,
    4,
    6,
    3,
    3,
    3,
    2,
    14
  ]
}

由于我无法更改输出它的程序,因此我必须自己使用sed(或awk) 来压缩 JSON 数组。理想的输出将是:

{
  "DaysCfg": {
    "Range": {
      "lowerDate": "2017-07-28T00:00:00.000-04:00",
      "upperDate": "2017-08-04T00:00:00.000-04:00"
    },
    "DaysInPeriod": 8,
    "DaysToSchedule": [0, 1, 2, 3, 4, 5, 6]
  },
  "DepartmentsID": [138837, 139734, 141934, 142436, 149687, 151049],
  "EmployeesID": [5039, 5170, 5889, 6051, 6236, 7208, 7281, 8776, 8781, 8936, 9261],
  "EndDate": "2017-08-03T23:59:00.000-04:00",
  "IntervalSize": 15,
  "IsActivitiesEnabled": true,
  "ModifyExisting": false,
  "OrignId": 134721,
  "PrimaryOption": 0,
  "SchoolDays": [],
  "ScChanges": [],
  "StartDate": "2017-07-28T00:00:00.000-04:00",
  "ZonesToSchedule": [5, 4, 6, 3, 3, 3, 2, 14]
}

我曾尝试自己编写一个sed脚本,但是它还不成熟并且无法完全发挥作用:

sed -r -e :a -e '/^ *[]}],*$/!N; /": \[/s/\n +//; ta' -e 'P;D'

请帮忙。谢谢。

答案1

我编辑了你的 sed,希望这会有所帮助。

sed -r '/\[$/ {:a;N;s/\]/&/;Ta;s/\n +//g}'

sed -r '

# sed will apply the commands between '{}' only to lines that matches the address '/\[$/'.
/\[$/ {

# Set a mark with label 'a'.
:a

# N command, it appends a '\n' to the pattern space,
# reads the next line of the input (file,stdin) and appends it to the pattern space.
N

# Substitute ']' for itself. If the substitution isn't made (if there isn't a ']' on the
# pattern space), the 'T' command jumps to the 'a' label.
# Here is the loop to put some lines (or all lines of a file) in the same line.
# While there isn't a ']' in the pattern space (which is the last line OP wants to put
# on the same line), sed will append '\n<next line>' to the pattern space.
s/\]/&/
Ta

# When the substitution is made, sed leaves the loop and applies other commands.
# Substitute all occurrences (g flag) of new line character (with any
# spaces after) for nothing.
s/\n +//g
}'

相关内容