4
I am trying to assemble a regular expression that can identify and correct an invalid JSON. What I am trying to do specifically is the following, using as an example the following JSON:
{
"array": [{
"id": "123",
"anotherObject": {
"name": "something"
},
"address": {
"street": "Dreamland",
"anotherArray": [
[3, 3]
[3, 3]
]
}
}]
}
In case the key anotherArray
is invalid since a ,
between the first and the second array. I wonder if it is possible to create a regex that can identify when a ]
is succeeded by a [
and add a comma in the middle using re.sub()
, for the end result to be this:
{
"array": [{
"id": "123",
"anotherObject": {
"name": "something"
},
"address": {
"street": "Dreamland",
"anotherArray": [
[3, 3],
[3, 3]
]
}
}]
}
The most I could do was (?<=])
but he finds all closes clasps, not only those who are succeeded by opens clasps.
Using a single regex and the way it was described in the accepted answer seems like a mistake. If you eventually have a JSON like this, "even if valid",
"street": "[foo] [bar]"
this will fail because the regex will cause something like:"street": "[foo], [bar]"
, which would change the string anyway and of course to you it may seem a little bit, but it’s just an example, something like this can cause a lot more things that you can’t predict To solve this you would probably need to create your own "parse", where you would identify "strings" and "keys", [...]– Guilherme Nascimento
[...] but I tell you, it will not be easy, you will have to do much more than a regex and also you will need to put a lot of logic for the script to know how to act in possible situations, an example of where I went through similar problem is that in my PHP framework I create a selector for CSS style DOM, when I run into a selector like this
[foo="abc[def]"]
because of the[
and]
failed, so I had to take everything isolate and unblock so that whatever was inside[]
was solved first and then would solve the ending. Other PHP selectors like phpquery fail because dev did not anticipate such problems.– Guilherme Nascimento