benbob
benbob

Reputation: 55

Append array data as objects to json file

I have a simple json file that has a direct image link and the folder name per json object:

[
        {
                "image": "http://placehold.it/350x150",
                "folder": "Small"
        },
        {
                "image": "http://placehold.it/450x250",
                "folder": "Medium"
        },
        {
                "image": "http://placehold.it/550x350",
                "folder": "Medium"
        }
]

I would like to append those two values from a post, but the result is an unchanged json file. Here is the PHP code w/ comments:

$directLink = $_POST['txtDirectLink'];
$category = $_POST['selectCategoriesImages'];
$util->addToJsonImageList($directLink, $category);

//decodes the json image list, merges to the decoded array a new image, then encodes back to a json file
function addToJsonImageList($link, $category) {
    $file = file_get_contents('./images_list.json', true);
    $data = json_decode($file);
    unset($file);

    $newImage = array('image' => $link, 'folder' => $category);
    //$newImage['image'] = $link;
    //$newImage['folder'] = $category;
    $result = array_merge((array)$data, (array)$newImage);

    json_encode($result);
    file_put_contents('./images_list.json', $result);
    unset($result);
}

The logic is that it should be simple to json_decode the file as an array, merge the new array onto that, then encode the result and put into the same file. I've been unable to capture any sort of errors either.

Upvotes: 3

Views: 22679

Answers (4)

Shadoworker
Shadoworker

Reputation: 191

Lets say you have this .json file named (playerJson)

{

"Players":
   [
     {"Name":"Arun","Arm":"Gun","num":"1"},
     {"Name":"sssv","Arm":"Arc","num":"2"},
     {"Name":"Surya","Arm":"Bomb","num":"3"},
     {"Name":"sssv","Arm":"Fire","num":"4"}

   ]
}

Now what we have to do in php (myPhpFile.php) is : (I suppose you are loading your data from a form)

<?php

$json = file_get_contents('playerJson.json');
$json_data = json_decode($json,true);

$newar = array(
           'Name'=>$_POST['nameField'] ,
           'Arm' =>$_POST['armField'],
           'Num' =>$_POST['numField']
);
//saving data in Players object...
array_push($json_data['Players'], $newar);

$json = json_encode($json_data);

file_put_contents('playerJson.json', $json);

?>

That's all ! You have a new line in your "Players" Object. But if you want to add a new object, avoid the [Players] after $json_data in the array_push function.

Upvotes: 1

bansi
bansi

Reputation: 56982

$data = json_decode($file, true);
//When TRUE, returned objects will be converted into associative arrays.
unset($file);

$newImage = array('image' => $link, 'folder' => $category);
//$newImage['image'] = $link;
//$newImage['folder'] = $category;
$result = array_merge($data, $newImage);
//don't need to cast

Reference PHP json_decode Manual

Edit The following code works (tested)

function addToJsonImageList($link, $category) {
    $file = file_get_contents('./images_list.json', true);
    $data = json_decode($file,true);
    unset($file);
    //you need to add new data as next index of data.
    $data[] = array('image' => $link, 'folder' => $category);
    $result=json_encode($data);
    file_put_contents('./images_list.json', $result);
    unset($result);
}

Edit 2 added lot of error reporting and debugging. Please let me know the output of the following. The code below is not tested (just typed in here).please fix if you find any syntax error. it is late here and can only check tomorrow my time, but can reply.

<?php
//display all errors and warnings
error_reporting(-1);
addToJsonImageList('test link', 'test category');

function addToJsonImageList($link, $category) {
    $file = file_get_contents('./images_list.json', true);
    if ($file===false)die('unable to read file');
    $data = json_decode($file,true);
    if ($data ===NULL)die('Unable to decode');
    unset($file);
    echo "data before\n";
    var_dump ($data);
    //you need to add new data as next index of data.
    $data[] = array('image' => $link, 'folder' => $category);
    echo "data after\n";
    var_dump ($data);
    $result=json_encode($data);
    if (file_put_contents('./images_list.json', $result) === false){
        die('unable to write file');
    }
    unset($result);
}
?>

Upvotes: 9

DevZer0
DevZer0

Reputation: 13525

your issue is with the following lines of code

json_encode($result);
file_put_contents('./images_list.json', $result);

your not capturing the result of json_encode so your writing an array into the file.

you need to adjust the code to read as follows

$result = json_encode($result);
file_put_contents('./images_list.json', $result);

Upvotes: 0

Dipesh Parmar
Dipesh Parmar

Reputation: 27364

What you can do is decode json and then merge them.

$data = json_decode(file_get_contents(./images_list.json));

$result = array_merge((array)$data, (array)$newImage);

and then just output json_encode

file_put_contents('./images_list.json', json_encode($result, JSON_FORCE_OBJECT));

Upvotes: 0

Related Questions