1

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"
    ]
}
4
  • 3
    You'll need to do this using whatever language your server runs ...at the server. Or use alternate storage Commented May 11, 2015 at 20:37
  • @charlietfl Is it possible to do this using PHP? I understand PHP quite well, but i haven't done PHP with JSON before. Commented May 11, 2015 at 20:39
  • php and json are simple...output any array or object using echo json_encode($array) in php Commented May 11, 2015 at 20:40
  • In php json is just a string unless you decode it to be an assosiative array or stdClass objects. Commented May 11, 2015 at 20:42

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.