自增ID JSON

3

我正在制作一个RESTful webservice,我希望发布到JSON文件中的条目都有一个ID。我已经到处搜索了,但是没有找到如何实现这一点的任何信息。

JSON的格式如下:

[
    {
        "id": "2",
        "title": "Hello World",
        "artist": "John Smith",
        "genre": "pop",
        "week": "4",
        "highest_rating": "3",
        "year": "2014",
        "youtube": "www",
        "links": [
            {
                "rel": "self",
                "href": ""
            },
            {
                "rel": "collection",
                "href": ""
            }
        ]
    },
    {
        "id": "3",
        "title": "Lorem Ipsum",
        "artist": "John Smith",
        "genre": "pop",
        "week": "4",
        "highest_rating": "3",
        "year": "2014",
        "youtube": "www",
        "links": [
            {
                "rel": "self",
                "href": ""
            },
            {
                "rel": "collection",
                "href": ""
            }
        ]
    }
]

这个文件中的id是硬编码的。 有人能告诉我如何使用自动增量获取id吗?
编辑: 我发现我没有清楚地解释我想做什么。 发布到Web服务的数据存储在一个.json文件中。 我没有使用数据库。 所以在PHP中,我正在做以下操作。
$file = file_get_contents("data.json");
    $data = json_decode($file, true);


    $data[] = array(
        'id'=>$_POST["id"],
        'title'=>$_POST["title"],
        'artist'=>$_POST["artist"],
        'genre'=>$_POST["genre"],
        'week'=>$_POST["week"],
        'highest_rating'=>$_POST["highest_rating"],
        'year'=>$_POST["year"],
        'youtube'=>$_POST["youtube"],
        "links"=> [ array(
                "rel"=>"self",
                "href"=>""
            ),
            array(
               "rel"=>"collection",
                "href"=>""
            )
        ]
    );

    file_put_contents('data.json',json_encode($data));

目前,id是通过POST方式提供的,但我希望它能够自动递增。

希望这样可以更清晰地表达我的问题。

4个回答

3

这取决于你的应用程序。如果你正在使用数据库,显然应该使用数据库主键值,但如果你将信息存储在简单的 .json 文件中,你必须自己声明每行的 id。获取最后一个并递增它。

我强烈建议你将这些数据存储在数据库中而不是文件中。你永远不会遇到事务问题(并发写入文件)。

更新

好的,根据你的代码:

$file = file_get_contents("data.json");
$data = json_decode($file, true);

// Get last id
$last_item    = end($data);
$last_item_id = $last_item['id'];

$data[] = array(
    'id'             => ++$last_item_id,
    'title'          => $_POST["title"],
    'artist'         => $_POST["artist"],
    'genre'          => $_POST["genre"],
    'week'           => $_POST["week"],
    'highest_rating' => $_POST["highest_rating"],
    'year'           => $_POST["year"],
    'youtube'        => $_POST["youtube"],
    "links"          => [ 
        array(
            "rel"=>"self",
            "href"=>""
        ),
        array(
            "rel"=>"collection",
            "href"=>""
        )
    ]
);

file_put_contents('data.json',json_encode($data), LOCK_EX);

我们在上面使用了LOCK_EX标志来在进行写入时获取文件的独占锁定
如果您无法使用DB,我认为使用flock()函数读写文件更加安全:
$filename = "data.json";
$filesize = filesize($filename);
$fp       = fopen($filename, "r+");

if (flock($fp, LOCK_EX))
{
    $data = json_decode(fread($fp, $filesize), true);

    // Get last id
    $last_item    = end($data);
    $last_item_id = $last_item['id'];

    $data[] = array(
        'id'             => ++$last_item_id,
        'title'          => 1,
        'artist'         => 2,
        'genre'          => 3,
        'week'           => 4,
        'highest_rating' => 5,
        'year'           => 6,
        'youtube'        => 7,
        "links"          => [
            array(
                "rel"  => "self",
                "href" => ""
            ),
            array(
                "rel"  => "collection",
                "href" => ""
            )
        ]
    );

    fseek($fp, 0);
    ftruncate($fp, 0);

    fwrite($fp, json_encode($data));

    flock($fp, LOCK_UN);
}
else
{
    echo "Unable to lock file";
}

fclose($fp);

确实是我正在寻找的。非常感谢你的帮助! - user3182261
最后一个问题。我现在收到警告:end()期望参数1为数组,在具有$last_item = end($data)的行中给出null。你知道为什么吗? - user3182261
抱歉,那是我的错误。我已经更新了代码以使其正常工作。 - Dmitriy Z
现在工作得非常好。非常感谢您的帮助! - user3182261

0

我在处理 JSON 数据时也遇到了同样的问题,但我的情况是将 JSON 存储在 MySQL 中,并且其中包含一些带有唯一 ID 的数据。

第一个示例可以工作,但如果您需要删除任何值,则再次添加值时它会获得重复的 ID,因此对我来说不起作用。

因此,如果您需要删除/添加值,并始终确保具有唯一的 ID,则我找到了一个简单的方法来实现这一点。

首先,您需要获取所有 ID,可以使用 array_column 函数轻松实现。

$idsList = array_column($data, 'id');

输出示例:[2,3]

然后你只需要简单地获取数组中最大的值(ID),并将其加上1。

$auto_increment_id = max($idsList) + 1;

就像我之前说的那样,这种方式可以让你始终编写唯一的ID。

也就是说,干杯!

根据你的代码,以下是完整的示例:

$file = file_get_contents("data.json");
$data = json_decode($file, true);

// Get IDs list
$idsList = array_column($data, 'id');
// Get unique id
$auto_increment_id = max($idsList) + 1;

$data[] = array(
    'id'             => $auto_increment_id,
    'title'          => $_POST["title"],
    'artist'         => $_POST["artist"],
    'genre'          => $_POST["genre"],
    'week'           => $_POST["week"],
    'highest_rating' => $_POST["highest_rating"],
    'year'           => $_POST["year"],
    'youtube'        => $_POST["youtube"],
    "links"          => [ 
        array(
            "rel"=>"self",
            "href"=>""
        ),
        array(
            "rel"=>"collection",
            "href"=>""
        )
    ]
);

file_put_contents('data.json',json_encode($data), LOCK_EX);

0
    "id": "2",
    "title": "Hello World",
    "artist": "John Smith"
    ...

你的JSON数据ID是字符串。请将其修改为

    "id": 2,
    "title": "Hello World",
    "artist": "John Smith"
    ...

0

虽然不清楚您想要自动递增的是什么,但当您的服务器收到请求后,可以遍历结果并添加所需的ID。

毕竟,您不能指望用户为每个数据结构提供您系统的内部ID。

就像MySQL不需要您提供ID一样,如果有自动递增的ID,则会自动生成。

我的建议:循环遍历传入的JSON并应用您自己的ID,从数据库或其他地方获取。


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