Insert object data into JSON file - javascript

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"
]
}

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.

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.

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

Related

How to append an item to a JSON stored in a file?

Im triying to write a JSON object to a DB with FS but it´s not working as expected. What i want to do is write the JSON data inside this: [] Example:
[
{"name":"jhon"},
{"name":"jhonathan"}
]
Here is the code:
Thanks.
The comment you provided doesn't make much sense, because the JSON data you provided in the post and in the comments is completely different. But I get the gist of it. I guess you have a JSON file containing an array and you want to push new items to it. Let's do this.
The thing is, when you call fs.appendFile, you're only writing to the end of the file. You're not following JSON format by doing so.
You need to do this:
Read file content.
Parse JSON text into an object.
Update the object in memory.
Write object in JSON format back to the file system.
I'll call the synchronous methods for simplicity's sake, but you should be able to convert it to async quite easily.
const path = __dirname + 'db.json'
// Reading items from the file system
const jsonData = fs.readFileSync(path)
const items = JSON.parse(jsonData)
// Add new item to the item list
items.push(newItem)
// Writing back to the file system
const newJsonString = JSON.stringify(items)
fs.writeFileSync(path, newJsonString)

update property in object loaded from js file - javascript

im very new in javascript and im trying to implement new function into existing project.
The background -
In html file i can see:
<script src="js/users.js" type="text/javascript"></script>
<script src="js/seating-plan.js"></script>
File seating-plan.js access object stored in users.js that contains:
var users = [
{"id": 1, "name":"first", "surname":"surname"},
{"id": 2, "name":"second", "surname":"surname"}
]
My question is: Can I change a property loaded from such object so the file will be changed? If so how to do it? I read some posts how to change object property but such approach will only changed already loaded object, not rewrite js file so i would be stuck with same result after refresh. Im guessing I will need to change how I initially load array object but if you know how to do it with my original aproach or how to do the second option in easy way please assist.
EDIT: localhost internal purpose (shared folder)
The approach I mentioned:
// Start of jQuery ready function
$(function () {
//can already access object
for (var i = 0; i < users.length; i++) {
//example of how i tried to rewrite property
if (users[i].id === 1){
users[i].name = "NewName";
}
}
.
.
.
If you want to change data on the server, then you must send an instruction to the server to change the data.
It would be a serious security risk if, by default, any web browser could change data on any HTTP server. The Google homepage would be vandalised on a second-by-second basis if that were possible!
Typically this will be a POST request (which you could make with a <form> or with XMLHttpRequest/fetch).
You then need server-side code (written in the language of your choice) which will update the data.
Typically you will want to store the data in a database and generate users.js (although changing it to JSON would probably be a better idea) on demand.

Save/Load Variables in js

I'm trying to create a save/load function for my game in js, but I have basically no idea with how to go through with doing this. I can save variables to a JSON file or LocalStorage, but I don't know how to load them back into the program. I'm also pretty sure I'm exporting variables the wrong way as well. Any help?
Normally, I use JSON format to store and read data (of any type).
To save data (using key gamedata as example):
var myData = {
name: 'David',
score: 10
}
localStorage.setItem('gamedata', JSON.stringify(myData));
** without JSON.stringify, you data will be saved as string [Object object]
To retrieve the data back:
var savedData = localStorage.getItem('gamedata'); // savedData is string
var myData = JSON.parse(savedData); // parse JSON string to java object
setup a bin on www.myJSON.com. p5 has built in functionality for ajax requests such as loadJSON. that way it's not in local storage and you can access your data if you have it on github. I know your struggle, I used to deal with this sort of issue myself before I found myJSON

process csv/json data in java servlets and javascript

I need an opinion on how to approach my problem. I have no idea on how to start and on how to implement which functions on which parts of the software. So this is what I want to do:
I have a Java servlet which creates a simple csv file:
name1, value1
name2, value2
etc.
This needs to be somehow converted to JSON data, so it can be displayed on a jsp page:
[
{
"name": "name1",
"value": "value1"
},
{
"name": "name2",
"value": "value2"
}
]
Then the user will be redirected to the jsp page. Is it possible to send the whole JSON structure via request object to the jsp page? Or is it the easiest if all processing is done in javascript and only the path to the csv file is sent via request object?
I'm kind of lost on this, since I first started last week with programming of web applications. I'd just need a push in the right direction and then I should be able to figure out the rest on my own ;)
First, look for a CSV parser which can turn a CSV file into a List<Bean> or List<Map<K,V>>.
Then, look for a JSON parser which can turn a List<Bean> or List<Map<K,V>> into a JSON string.
Finally, just do the math and set the resulting JSON string as a request attribute which you print in JSP as if it's a JS variable, like so <script>var data = ${data};</script>.

Read JavaScript variables from a file with Python

I use some Python scripts on server-side to compile JavaScript files to one file and also add information about these files into database.
For adding the information about the scripts I now have yaml file for each js file with some info inside it looking like this:
title: Script title
alias: script_alias
I would like to throw away yaml that looks redundant here to me if I can read these variables directly from JavaScript that I could place in the very beginning of the file like this:
var title = "Script title";
var alias = "script_alias";
Is it possible to read these variables with Python easily?
Assuming you only want the two lines, and they are at the top of the file...
import re
js = open("yourfile.js", "r").readlines()[:2]
matcher_rex = re.compile(r'^var\s+(?P<varname>\w+)\s+=\s+"(?P<varvalue>[\w\s]+)";?$')
for line in js:
matches = matcher_rex.match(line)
if matches:
name, value = matches.groups()
print name, value
Have you tried storing the variables in a JSON format? Then, both javascript and python can easily parse the data and get the variables.

Categories

Resources