Edward
Edward

Reputation: 23

Insert object data into JSON file

I know that it's possible to read and get data of JSON file, but I didn't find any information on how to write an object to JSON file using jQuery. I understand some jQuery, but I dont have any idea how I could do this.

This is the structure of my JSON file:

{
    "1": [
        "6-5-2015", 
        "7-5-2015", 
        "10-5-2015"
    ]
}

This is an object variable that I want to write into JSON file:

var object = {"2": ["9-5-2015", "14-5-2015", "22-5-2015"]};

How can I push or insert this object to the end of my JSON file and save it, so that the JSON file could look like this?

{
    "1": [
        "6-5-2015", 
        "7-5-2015", 
        "10-5-2015"
    ],
    "2": [
        "9-5-2015", 
        "14-5-2015", 
        "22-5-2015"
    ]
}

Upvotes: 1

Views: 2334

Answers (3)

Stefan Kanev
Stefan Kanev

Reputation: 311

You cannot write a file locally but you can save cookies locally. For managing cookies with JS you can use a plugin available here..

https://github.com/carhartl/jquery-cookie

//set
    var object = {"2": ["9-5-2015", "14-5-2015", "22-5-2015"]};
    $.cookie("mydata", object );
    ....
//get
    var object = jQuery.parseJSON($.cookie('mydata'));

Upvotes: 0

chriss
chriss

Reputation: 669

You can't. JavaScript does not access your disc so it can't directly write into file, so You should have some server side logic.

Reason why it can read that file because on your dist location of that file is URL. But URL on Your drive.

Upvotes: 0

taxicala
taxicala

Reputation: 21769

You cannot write a file locally with Javascript, that would be a major security concern. I suggest you to move the file to your server and do a Public Api where you send the new content and write it server-side. Then request by GET the file in order to read it. Remember that you will have to lock and release the file accordingly in order to avoid loosing changes between requests.

Upvotes: 2

Related Questions