'Auto increment id JSON

I'm making a RESTful webservice and I want the items that are posted to the JSON file to have an Id. I've been searching everywhere but couldn't find anything on how to do this.

The JSON looks like this

[
    {
        "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": ""
            }
        ]
    }
]

The id's in this file are hardcoded. Can someone please tell me how to get id's with auto increment

Edit I see I've been unclear in explaining what I want to do.

Data that is posted to the webservice, is stored in a .json file. I'm not using a DB. So in PHP, this is what I'm doing.

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

So at the moment the id is given through a POST but I want it to be given with auto-increment. I hope this makes my question clearer.



Solution 1:[1]

It depends on your application. If you're using DB you obviously should use DB primary key value, but if you're store your info in simple .json file you must declare each row id yourself. Get the last one and increment it.

I'm strongly recommend you to store this data in DB not in file. You'll never have problems with transactions (concurrent writing to file).

Update

OK, depending on your code:

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

We're using LOCK_EX flag above to acquire an exclusive lock on the file while proceeding to the writing.

If you can't use DB I think it's more safely to read and write file with flock() function:

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

Solution 2:[2]

While it's not clear from what you want to auto increment, When your server gets the post, it can iterate over the result and add the required ID.

After all, you can't expect the user to give you an internal id for your system for every data strcutre he passes you.

Just the same way mysql doesn't expect you to provide an id if there's an id that's auto increment.

My suggestion : Loop over the incoming json and apply your own id, from the db or what not.

Solution 3:[3]

I had the same problem with JSON, but in my case it's JSON in MySQL, where i store some data, with unique IDs.

The first example works, but when you need to remove any values,next time you add a value it would get duplicate IDs, so it doesn't works for me properly.

So if you need to remove/add values, and always to be sure to have unique IDs, there's simple way i found to do that.

Firstly, you get all the IDs, the array_column function is doing that just the right way

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

Output example: [2,3]

Then you just simply get the biggest value(ID) on the array, and add to the value +1.

$auto_increment_id = max($idsList) + 1;

So as i already said, this way you will write always an unique ID.

That is, Cheers!

Full example depending on your code:

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

Solution 4:[4]

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

your JSON Data ID is string. Make it like

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Patrick
Solution 3 Georgy Sharapov
Solution 4 Enes ÇEB