0

So I have got a string that looks like below that I am trying to break up with regex.

[{"id":...,"fieldA":"data","adjustments":[{"id":....,"fieldA":"data"},{"id":....,"fieldA":"data"}],"fieldB":"data"},{"id":...,"fieldA":"data","adjustments":[],"fieldB":"data"}]

The goal is to group the strings between the, let's say parent, curly brackets.

The result would look like this

Group 1:

{"id":...,"fieldA":"data","adjustments":[{"id":....,"fieldA":"data"},{"id":....,"fieldA":"data"}],"fieldB":"data"}`

Group 2:

{"id":...,"fieldA":"data","adjustments":[],"fieldB":"data"}]

Now the string can have more of the parent {} strings and there can be more than 2 child {} within the parent.

What the frick do I use?

Andy A.
  • 1,392
  • 5
  • 15
  • 28
Hamii
  • 1
  • 2
    `What the frick do I use?` - You use the right tools for the job. Regex is not one of them. You have a json string from the appearance of it, if that is the case parse that thing as json and do your bidding in your language of choice instead of trying to write a json parser in regex. – Mat J Jul 09 '21 at 06:04
  • If you want really use regex, check [regex101](https://regex101.com) and maybe [Debuggex](https://debuggex.com). – Andy A. Jul 09 '21 at 07:07

2 Answers2

0

This is not a good problem for regex. See RegEx match open tags except XHTML self-contained tags for details.

I would advise parsing this in a language like Python or Javascript, and then doing your transformations there.

ddg
  • 1,090
  • 1
  • 6
  • 17
0

If you have PowerShell available to you

$json = '[{"id":"...","fieldA":"data","adjustments":[{"id":"....","fieldA":"data"},{"id":"....","fieldA":"data"}],"fieldB":"data"},{"id":"...","fieldA":"data","adjustments":[],"fieldB":"data"}]'

# Convert Json to objects
$jsonObjects = $json | ConvertFrom-Json

# Convert each individual object back to json
$splitJson = $jsonObjects | ForEach-Object { $_ | ConvertTo-Json -Compress }

# Send output to file
$splitJson | Out-File C:\temp\json_split.json

# Send output to screen
$splitJson

Output

{"id":"...","fieldA":"data","adjustments":[{"id":"....","fieldA":"data"},{"id":"....","fieldA":"data"}],"fieldB":"data"}
{"id":"...","fieldA":"data","adjustments":[],"fieldB":"data"}
Daniel
  • 4,792
  • 2
  • 7
  • 20