0

I have text per below (from an api response).

$a = '[
  {
    "Id": "65486432",
    "RecordType": 20
  },
  {
    "Id": "d1b2abe9",
    "RecordType": 20,
    "ModelsSnapshots": []
  }
]
[
  {
    "Id": "65486432",
    "RecordType": 20
  },
  {
    "Id": "d1b2abe9",
    "RecordType": 20,
    "ModelsSnapshots": []
  }
]'

I need to replace the square brackets in the middle with ","

]
[

So the final output should be like. Note there are also "[]" in the text that I don't want to change.

'[
  {
    "Id": "65486432",
    "RecordType": 20
  },
  {
    "Id": "d1b2abe9",
    "RecordType": 20,
    "ModelsSnapshots": []
  }
,
  {
    "Id": "65486432",
    "RecordType": 20
  },
  {
    "Id": "d1b2abe9",
    "RecordType": 20,
    "ModelsSnapshots": []
  }
]'

I've tried the following with no luck:

$a -replace "\]`n\[", ","

This works in this example, but not in the actual file, so other alternative solutions would be appreciated.

stackprotector
  • 10,498
  • 4
  • 35
  • 64
woshishui
  • 1,906
  • 2
  • 15
  • 22

2 Answers2

0

Your file may contain CR&LF instead of LF only. I recommend to use the following regex to be safe in both cases:

$a -replace "\]`r?`n\[", ","
stackprotector
  • 10,498
  • 4
  • 35
  • 64
0

it's somehow not a newline between "]" and "[", there has to be a better way of doing this, but the following is working.

first i replaced the "[]" with a place holder "XXXX", then remove "]" and "[", and finally replace "XXXX" back with "[]"...

$a -replace "\[]", "XXXX" -replace "\[", "" -replace "\]", "" -replace "`n"," " -replace "`r"," " -replace "\Z", "," -replace "XXXX", "[]"
woshishui
  • 1,906
  • 2
  • 15
  • 22