Add information to a. json file

Asked

Viewed 170 times

0

You can add information with a different reference to a json file with php?

Type:

file json.

{ 
     'id': 'rt6hj7'{
          'nome':'Miguel'
      },
      'id': 'rt10hg9'{
          'nome':'Sagas'
      } 
}

And add Jose with id: 8dhus8763 and not subscribe to any information already contained in the file. Make file.json into a kind of database.

Someone has an idea?

I appreciate help

  • Yes it is possible although it is not advisable. Put the code there.

  • "Not being advisable" is not true, it all depends on what he wants to do with it. JSON is a great way to store diverse settings from the application, and sometimes you need to modify these settings programmatically. It is also interesting to use JSON as a database in some cases specific good, such as a very simple application that will only be used locally by just one user. Now @user2647038 in case you want to make a web app accessed by several users, or that has multiple entities (read tables in the database) it is really advisable to use a JSON.

1 answer

0

Yes, it is possible, however first note that your JSON structure is invalid, this doesn’t make sense here 'id': 'rt6hj7'{ then you should start using a valid JSON, ex:

{
   "rt6hj7": {
        "nome": "Miguel"
    },
    "rt10hg9": {
        "nome": "Sagas"
    }
}

Now assuming that this structure above is in file.json, we can yes add Keys with something like:

// pega o conteúdo do file.json e transforma em um php array
$data = json_decode(file_get_contents('file.json'), true);
// adiciona "José" sob a id "8dhus8763"
$data['8dhus8763'] = ['nome' => 'José'];
// salva seu novo JSON
file_put_contents(json_encode($data));

The idea is bascimante: takes the content of JSON -> transforms the JSON string into a PHP array -> adds the object with "name": "José" in the array, the id being "8dhus8763" -> transforms your PHP array into a JSON string -> saves the JSON string in the original file.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.