简体   繁体   中英

How to store jQuery or javascript variable in json file?

Could I know that is there any chance to save the jquery variable in json file ? Thanks in advance.

I have:

var image='/test/test.png';

I'm getting this path with my file upload

<input type="file" name="imageurl" value="imagefile"></input>

so, I have to save it in json file

like: [{"name":"imageurl","value":"/test/test.png'"}]

Please find my code:

html:

<form id="testId">
    <input type="hidden" value="/test/test1.png" name="Image1">
    <input type="hidden" value="/test/test2.png"  name="Image2" >
   <input type="file" name="imageurl" value="imagefile"></input>
   <input type="hidden" value="imagefile"  name="imageurl"></input>
  <input type="button" value="Submit" id="testFile"></input>
</form>

jQuery:

var imagepath =$('input[type=file]').val().replace(/C:\\fakepath\\/i, '');//test.png
var image = '/test/'+imagepath;

my json file:

[{"name":"Image1","value":"/test/test1.png"},{"name":"Image2","value":"/test/test2.png"}]

but my required json file is:

[{"name":"Image1","value":"/test/test1.png"},{"name":"Image2","value":"/test/test2.png"},{"name":"imageurl","value":"/test/test3.png"}]

Please let me know any solution for it.

Use the following

var value=JSON.stringify($(form).serializeArray());

The above statement will return key value pairs of the form fields.

You can write data to a json file using node js.

If file already exists the you can use

fs.appendFile('jsonsample.json', value, function (err) {

});

For writing new file you can use

fs.writeFile('jsonsample.json', value, function (err) {

});

To manipulate the json objects that are read from file and rewriting data you can read the following resource as a starter

https://www.codementor.io/nodejs/tutorial/how-to-use-json-files-in-node-js

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