I want to change my JSON file or add an element to my SON file, but real file. I tried this code, but it doesn’t work on the real file. Only the time the tab is open on the web has changed. How to handle it in real file? Not user file, it is server file, but I tried my local.
let xmlreq = new XMLHttpRequest() xmlreq.open("GET","users.json",true) function test(){ const obj = JSON.parse(xmlreq.responseText); console.log(obj); obj.user1.name="john"; console.log('obj.user1.name: ', obj.user1.name); obj.user2.push("item"); console.log('obj.user2.: ', obj.user2); } xmlreq.send()
another
let xmlreq = new XMLHttpRequest() function test(){ // let parsereq= JSON.parse(xmlreq.responseText); const obj = JSON.parse(xmlreq.responseText); console.log(obj); obj.user1.name="john"; console.log('obj.user1.name: ', obj.user1.name); obj.user2.push("item"); console.log('obj.user2.: ', obj.user2); } xmlreq.open("GET","users.json",true) xmlreq.send()
Advertisement
Answer
First you have to use the File API to load the file.
https://developer.mozilla.org/en-US/docs/Web/API/File
Then you have to parse the JSON data.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Then you can do your modifications.
But you can not modify files on your local disc directly. Instead you have to download the file in order to overwrite the original file.
To do so you have to create a data URL from your JSON data.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
And finally you can create a link to download the new JSON.