I'm new to php and am trying to parse a string I'm getting. The string is the result of a bash script I'm running, and I'm storing the output into a php variable. Here is the output I'm getting:
1/1 [==============================] - 1s 1s/step
[
{
"image_id": "mahomes1",
"mean_score_prediction": 6.3682564571499825
},
{
"image_id": "mahomes2",
"mean_score_prediction": 6.7501190304756165
},
{
"image_id": "mahomes3",
"mean_score_prediction": 6.3136263862252235
},
]
How would I go about parsing this string so that I can create a dictionary that stores the "image_id"
value with the "mean_score_prediction"
value?
Your data is almost valid JSON, other than the beginning text and the comma between the final }
and closing ]
. By cleaning those issues up, you can then use json_decode
on it to get a dictionary as an array of objects (or arrays, dependent on your preference):
$string = preg_replace(array('/^[^\v]+/', '/,(\s+\])/'), array('', '$1'), $string);
$dict = json_decode($string);
print_r($dict);
Output:
Array (
[0] => stdClass Object (
[image_id] => mahomes1
[mean_score_prediction] => 6.36825645715
)
[1] => stdClass Object (
[image_id] => mahomes2
[mean_score_prediction] => 6.7501190304756
)
[2] => stdClass Object (
[image_id] => mahomes3
[mean_score_prediction] => 6.3136263862252
)
)
To get an array of arrays, call json_decode
with a second parameter of true
i.e.
$dict = json_decode($string, true);