Assuming that your string is composed of valid JSON object put together without any delimiter, you can do the following:
- Split the string with
}{
as delimiter
- Loop over each item in the resulting array and add the missing parts
- Merge the array into one string with a
,
as delimiter
- Add the JSON array marks before and after the string
Example (with $input
as the input string):
$chunks = explode('}{', $input);
$n = count($chunks);
for($i = 0; $i < $n; $i++) {
if($i == 0) {
$chunks[$i] = $chunks[$i].'}';
} else if($i == $n - 1) {
$chunks[$i] = '{'.$chunks[$i];
} else {
$chunks[$i] = '{'.$chunks[$i].'}';
}
}
$output = '['.implode(',', $chunks).']';
Note that it will work on imbricated structures, but will miserably fail if you have a }{
in the text. But it is unlikely.
EDIT: One simple way of checking if the current chunk is a wrong cut could be by checking is the next chunk start with a "
, because JSON object's attributes are always quoted. If not, then you can merge the current and next chunk and repeat until finding the right character.