Save data in Json with javascript

0

Hi, I have a file comments.json that contains the following:

{
    "comments": [
        {
            "id": 1,
            "post_id": 2,
            "name": "Javi",
            "email": "[email protected]",
            "body": "Esto es un post",
            "created_at": "2017-12-29"    
        },
        {
             "id": 2,
            "post_id": 1,
            "name": "Pepe",
            "email": "[email protected]",
            "body": "Otro post de pepe",
            "created_at": "2017-12-29" 
        }
    ]
}

How can I add the following to this file:

{
             "id": 3,
            "post_id": 1,
            "name": "Juan",
            "email": "[email protected]",
            "body": "nuevo post",
            "created_at": "2017-12-29" 
        }
    
asked by Javier Alonso Lopez 04.01.2018 в 12:25
source

1 answer

3

Hello! I do not think it is good policy to use a manually managed .json file as a database, I would recommend using some SQL or noSQL (Firebase saves in Json for example).

In any case if it is essential to do it this way you can do the following (written in php, but in any language you can do the same):

$contenido = file_get_contents('path/to/comments.json');
$contenido_arr = json_decode($contenido, true);
$contenido_arr['comments'][] = [
"id" => 3,
"post_id" => 1,
"name" => "Juan",
"email" => "[email protected]",
"body" => "nuevo post",
"created_at" => "2017-12-29" 
];
$json = json_encode($contenido_arr);
file_put_contents('path/to/comments.json', $json);

I must insist that I would not recommend doing this, unless absolutely necessary. Greetings and luck!

    
answered by 04.01.2018 в 12:58