1

I have a JSON file containing this text:

[
  {
    "key" : "test1",
    "desc": "desc1"
  },
  {
    "key" : "test2",
    "desc": "desc2"
  },
]

I made a code to read the content of this file (using AJAX) and to display the content into an HTML table.

Now, i would like to be able to update a value in my HTML array and save the modification into the JSON file.

Is it possible in JavaScript?

wawanopoulos
  • 9,614
  • 31
  • 111
  • 166
  • "display the content into an HTLK table" Did you mean HTML? – Michał Perłakowski Aug 26 '15 at 10:04
  • you can store the js and then modify when the html is modified else if you want to send the json on click of a button you can regenerate the json fro m the html or you can use the data- attrs to store the json in any tag you wish and update when html updates – joyBlanks Aug 26 '15 at 10:04
  • i would suggest you to parse JSON into JavaScript object(using JSON.parse() method), and modify the content in JavaScript object. Now once you done with changes, you could simply convert back the JavaScript object to JSON(using JSON.stringfy() method), and pass the content to server, where you can re-write the file using any server side code. – Akshay Aug 26 '15 at 10:13

2 Answers2

1

You need a server-side technology to modify file contents. If you use PHP is as simple as read file, transform to an array and modify the value that you need, and then return the json decode value to write the file again.

If you use only javascript, maybe you need to use Node.js as server-side solution.

Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
0

You should use server-side script. Below is my php code:

First, you need to decode it :

$jsonString = file_get_contents('jsonFile.json');
$data = json_decode($jsonString);

Then change the data :

$data[0]['desc'] = "TENNIS";
// or if you want to change all entries with key "1"
foreach ($data as $key => $entry) {
    if ($entry['key'] == 'test1') {
        $data[$key]['desc'] = "TENNIS";
    }
}

Then re-encode it and save it back in the file:

$newJsonString = json_encode($data);
file_put_contents('jsonFile.json', $newJsonString);

Above is sample, but you can unserstand the logic.

Muhammet Arslan
  • 975
  • 1
  • 9
  • 33