user3182261
user3182261

Reputation: 271

Adding data to json

I'm making a RESTful webservice and I want to add data to a JSON file. I'm now getting errors and warnings and I can't figure out what I'm missing or doing wrong.

The JSON file looks like this

    {
    "charts": {
        "title": "Top 40",
        "song": {
            "id":"1",
            "title": "Title",
            "artist": "Name" ,
            "genre": "Something",
            "weeks": "4",
            "highest_rating": "18",
            "year": "2014",
            "youtube": "link here"
        }
    }
}

I want to get something like this when data is added

 {
        "charts": {
            "title": "Top 40",
            "song": {
                "id":"1",
                "title": "Title",
                "artist": "Name" ,
                "genre": "Something",
                "weeks": "4",
                "highest_rating": "18",
                "year": "2014",
                "youtube": "link here"
                }
               {
                "id":"2",
                "title": "Title",
                "artist": "Name" ,
                "genre": "Something",
                "weeks": "4",
                "highest_rating": "18",
                "year": "2014",
                "youtube": "link here"
            }
        }
    }

The PHP code I'm using is this

EDIT Added more code to be more complete

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

    $data->charts->songs[] = 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"]
    );

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

Upvotes: 0

Views: 83

Answers (2)

Cormac Mulhall
Cormac Mulhall

Reputation: 1217

You are trying to access the multi-dimensional array produced by json_decode as if it was an object.

Replace this line

$data = json_decode($file, true);

with this

$data = json_decode($file, false);

if you want the result to be objects rather than a multi-dimensional array.

On other hand if you are happy that $data is a multi-dimensional array then access it like this

$data['charts']['songs'][] = array(

http://php.net/manual/en/function.json-decode.php

Upvotes: 2

Mohan S Gopal
Mohan S Gopal

Reputation: 233

try json_encode function. $data->charts[] = json_encode($_POST);

Upvotes: 0

Related Questions