将数组数据作为对象添加到JSON文件中

3

我有一个简单的JSON文件,每个JSON对象都包含一个直接的图像链接和文件夹名称:

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

我希望能够将来自post请求的两个值附加到一起,但结果是未更改的json文件。以下是带有注释的PHP代码:

$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);
}

逻辑是将文件解码为数组,合并新数组,然后编码结果并放回同一文件。我无法捕获任何错误。

尝试使用 $data = json_decode($file,true); 进行解码。 - bansi
我以为我已经做过了,以确保它返回一个数组,但我不小心在文件中添加了bool参数。然而仍然没有改变。 - benbob
file_put_contents('./images_list.json', json_encode($result)); - Alejandro Iván
4个回答

9
$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

参考PHP的json_decode手册

编辑 下面的代码是有效的(已测试)

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);
}

编辑 2 加入了大量错误报告和调试信息。请让我知道以下输出结果。下面的代码没有经过测试(只是在这里打字)。如果您发现任何语法错误,请修复。目前已晚,在我的时间明天才能检查,但可以回复。

<?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);
}
?>

我现在收到一个"array_merge: argument #1 is not an array"的错误。 - benbob
我尝试了编辑后的代码,但是它仍然没有改变我的json文件...有没有错误检查工具可以帮助我找出问题所在?这个json文件也在同一个目录下。 - benbob
太棒了,有了你的错误检查,我终于让它工作了。不过我注意到一个json文件中有一件事情与之前不同:任何http://字符串都变成了http://(编码会这样做吗?)。感谢你的帮助和时间,我会研究转义斜杠的问题。 - benbob
很高兴听到它对你有用。即使在JSON中不需要,正斜杠也会被转义。请查看此帖子以获取更详细的讨论。https://dev59.com/YHI-5IYBdhLWcg3w-92b - bansi
很高兴听到它可以安全地被忽略 :) - benbob
我尝试了第一个编辑,它起作用了,但是我该如何在JSON数组的开头添加内容? - pavitran

1
假设您有一个名为(playerJson)的 .json 文件。
{

"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"}

   ]
}

现在我们需要在php中(myPhpFile.php)完成以下操作:(我假设您正在从表单中加载数据)
<?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);

?>

就这些!您的“Players”对象中有一行新内容。但是如果您想添加一个新对象,请避免在array_push函数中使用$ json_data后面的[Players]。


0
你可以解码 JSON 然后合并它们。
$data = json_decode(file_get_contents(./images_list.json));

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

然后只需输出json_encode

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

我在file_put_content中添加了json_encode(result),现在收到错误消息:“array_merge(): Argument #1 is not an array”,尽管我将$data设置为数组而不是对象,通过添加可选的true。 - benbob

0

你的问题出在以下代码行

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

你没有捕获json_encode的结果,所以你正在将一个数组写入文件。

你需要调整代码,使其如下所示

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

我应该更新我的答案,因为我已经解决了那个问题。不过还是谢谢你的见解。 - benbob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接