How to convert a string separated by square brackets with comma into valid json object in php?

Viewed 26

I got a specific string that I want to convert into a JSON object in PHP

The string is: ['Spring', '>30'], ['JPA', '>30'], ['Hibernate', '>30'], 1

Here is what I tried so far:

$catwidfieldval = "['Spring', '>30'], ['JPA', '>30'], ['Hibernate', '>30'], 1"; $jsonrt = json_decode ($catwidfieldval, true); var_dump ($jsonrt);

Result of above code: NULL

This is what I want to achieve:

[ 0:[ 0:Spring 1:>30 ], 1:[ 0:JPA 1:>30 ], 2:[ 0:Hibernate 1:>30 ] ]

Note: Last Index is not required in JSON object eg like 1 in the above string

Thanks

1 Answers

The formats given is no valid JSON. So you need to parse it yourself.

You could go with a regex to find the content between the square brackets. Then loop over those to extract the values between the quotes.

$string  = "['Spring', '>30'], ['JPA', '>30'], ['Hibernate', '>30'], 1";
$matches = [];
preg_match_all('/\[(.*?)\]/', $string, $matches);
foreach ($matches[1] as $index => $match) {
    $matches2 = [];
    preg_match_all('/\'(.*?)\'/', $match, $matches2);
    $parts[] = "$index:[ 0:{$matches2[1][0]}, 1:{$matches2[1][1]} ]";
}
$result = '[ ' . implode(', ', $parts) . '] ';
echo $result;
[ 0:[ 0:Spring, 1:>30 ], 1:[ 0:JPA, 1:>30 ], 2:[ 0:Hibernate, 1:>30 ]]

Update

As you commented you would like valid json you can do like this if you dont want each pair to be an array.

$string  = "['Spring', '>30'], ['JPA', '>30'], ['Hibernate', '>30'], 1";
$matches = [];
$parts = [];
preg_match_all('/\[(.*?)\]/', $string, $matches);
foreach ($matches[1] as $index => $match) {
    $matches2 = [];
    preg_match_all('/\'(.*?)\'/', $match, $matches2);
    $parts[$matches2[1][0]] = $matches2[1][1];
}
$json = json_encode($parts);
echo $json;
{"Spring":">30","JPA":">30","Hibernate":">30"}

or change the $parts line with

$parts[] = [$matches2[1][0] => $matches2[1][1]];

to get

[{"Spring":">30"},{"JPA":">30"},{"Hibernate":">30"}]
Related