How to create good json file

json file
{
“data”: {
“index”: “6”,
“partia”: “”,
}
},{
“data”: {
“index”: “13”,
“part”: “”,
}
},

Php file:

<?php 
 
 
$unsafe_json = json_decode( $_GET["data"], true );
 
if( ! is_array( $unsafe_json ) ) {
 
 
die('error save');
}
 
 
$safe_json = [ 'data' => [] ];
 
$values = [ 'index', 'part' ];
 
foreach( $unsafe_json as $unsafe_todo ) {
$safe_todo = [];
 
foreach( $values as $value ) {
    if( isset( $unsafe_todo[$value] ) && is_string( $unsafe_todo[$value] ) ) {
        $safe_todo[$value] = filter_var( $unsafe_todo[$value], FILTER_SANITIZE_STRING );
    } else {
        $safe_todo[$value] = false;
    }
}
 
$safe_json['data'][] = $safe_todo;
}
$json_decoded = json_decode($json_encoded, true);
foreach ($json_decoded as $i => $object)
if ($object['data']['index'] == 1)
    unset($json_decoded[$i]);
// save to file
$file = fopen( "todo.json", "a" ); 
fwrite( $file, '' . json_encode(  $safe_json, JSON_PRETTY_PRINT ) . ',' ); 
fclose( $file ); 
 
$data = file_get_contents('todo.json');

And i don’t know how create good json format in todo.json

Appending to a JSON file mostly makes no sense. The comma at the end would invalidate the file. You have to decode the file, make your changes on the resulting array, and save everything back with json_encode. Altering a JSON file manually has a high risk of breaking the syntax.

Could you show me how can I do this? Becouse i am newbie in php and i can’t do this

You create and array with keys then encode it.

$json =  file_get_contents($in); // get file
$array = json_decode($json); // get contents
$array[] = 'something new'; // modify contents
$json = json_encode($array); // write contents
file_put_contents($json, $out); // write file
1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service