-1

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()
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • It's not exactly clear from your question. But in case you are trying to change a file in the user's harddrive, you can't. Unless you are running a server that accepts files and replaces them you have no access to writing or changing any files – Aram Becker Aug 25 '21 at 05:44
  • By the way, you can include code (and images too) directly in your question, you don't need to use image links. – Aram Becker Aug 25 '21 at 05:45
  • Also, I don't see how your code would change anything the the json there? You define a function test and never call it. And then you are doing a get request, that's it – Aram Becker Aug 25 '21 at 05:45
  • @AramBecker you can see i am new on this site so I can't upload photos directly and i try a database for users .just try on my computer , not the user computer , You can think of it as a server. – Hüseyin Cuma Aug 25 '21 at 06:52
  • I still don't understand what you are trying to achieve. Can you provide the json input, the desired json output and what exactly you mean by save? – Aram Becker Aug 25 '21 at 10:40
  • @AramBecker Sorry, my fault, I didn't explain myself properly. What I want to do is to print data to a .json file using javascript. I hope I can explain now. – Hüseyin Cuma Aug 27 '21 at 13:49

1 Answers1

0

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.

https://stackoverflow.com/a/15832662/402322

ceving
  • 21,900
  • 13
  • 104
  • 178