Adam Projo Adam Projo - 1 month ago 5
Javascript Question

Error in decode json code

i need help with decode json



if($loop->have_posts()) :
$json = '{';
$json .= '
"api_status":1,
"api_message":"success",
"data": [';
while ( $loop->have_posts() ) : $loop->the_post();
$json .= '{
"id":'.get_the_ID().',
"post_name":"'.get_the_title().'"
},
';
endwhile;

$json = substr($json,0,-1);
$json .= ']}';

echo $json;
endif;
break;
}




my error is

enter image description here

in the last
}
i have still
,
so i need to remove it.

but i dont know how ?
someone help me ?

Answer

use rtrim($json, ","); to remove last comma from json output

if($loop->have_posts()) :
    $json = '{';
    $json .= '
    "api_status":1,
    "api_message":"success",
    "data": [';
    while ( $loop->have_posts() ) : $loop->the_post();
        $json .= '{
        "id":'.get_the_ID().',
        "post_name":"'.get_the_title().'"
        },';
    endwhile;


    $json = rtrim($json, ",");
    $json .= ']}';

    echo $json;
endif;
break;
}

another way

$json = new array();
if($loop->have_posts()) :
    $json["api_status"] = 1,
    $json["api_message"] = "success",
    $json["data"] = new array();
    while ( $loop->have_posts() ) : $loop->the_post();
        $json["data"]["id"] = get_the_ID();
        $json["data"]["post_name"] = get_the_title();
    endwhile;
    echo json_encode($json);
endif;
break;
}
Comments