我是php的新手,正在尝试解析一个字符串。该字符串是我运行的bash脚本的结果,并将输出存储到php变量中。这是我得到的输出:
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
},
]
我将如何解析此字符串,以便创建一个字典来存储"image_id"
值和"mean_score_prediction"
值?
答案 0 :(得分:0)
您的数据几乎是有效的JSON,除了开头的文本以及结尾的}
和结尾的]
之间的逗号之外。通过清理这些问题,然后可以在其上使用json_decode
来将字典作为对象数组(或数组,取决于您的偏好):
$string = preg_replace(array('/^[^\v]+/', '/,(\s+\])/'), array('', '$1'), $string);
$dict = json_decode($string);
print_r($dict);
输出:
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
)
)
要获取数组数组,请使用第二个参数json_decode
调用true
,
$dict = json_decode($string, true);