简体   繁体   中英

How to write data to a JSON file using Javascript

For example, I have a .JSON<\/code> file that has the following:

[{"honda": "accord", "color": "red"},{"ford": "focus", "color": "black"}]

You have to be clear on what you mean by "JSON".

This one happens to be an array. If you want to add a new element to the array, just push<\/code> it, as in

var arr = [{a: 1}];
arr.push({b: 2});

< [{a: 1}, {b: 2}]

JSON can be written into local storage using the JSON.stringify to serialize a JS object. You cannot write to a JSON file using only JS. Only cookies or local storage

    var obj = {"nissan": "sentra", "color": "green"};

localStorage.setItem('myStorage', JSON.stringify(obj));

Unfortunatelly, today (September 2018) you can not find cross-browser solution for client side file writing.

Although it may still work in some browsers, its use is discouraged since it could be removed at any time.<\/em> Try to avoid using it.<\/em>


<\/blockquote>

If you want update your JSON file cross-browser you have to use server and client side together.<\/strong>

<\/h2> Or you could read a file with FileReader<\/a><\/strong> too. For the cross-browser writing to the file you have to have some server (see below on server part).

<\/h2>

You can use a lot of different servers, but I would like to write about PHP and Node.js servers.

For PHP server I would recommend 000webhost.com<\/a> and for Node.js I would recommend to see and to read this list<\/a> .

This is not normal JavaScript like in browser. Before you start with Node.js I would recommend to read one from two books:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM