Lets say I have a JSON file, with an array inside of that JSON file.
{
"users": ["288381238123", "12312123123"]
}
Now I want to push to that array, and I have that file required at the top
const userList = require('../rolecall.json');
Then I have some other code here, which is seemingly supposed to push to that array
const users = userList.users;
users.push('82313123');
Now when I check back to the JSON file, there is no addition to the array. Why is that? If anyone could help me, that would be great.
When you 'push' to the array in Javascript, you are only changing the Javascript object.
Edit: taking Lyon's comment into account
The short answer is, you can't change a file on the client machine using javascript. That would be a huge security issue (though it used to be possible, fun times).
However, you can ask the browser to display a save dialog asking the user whether they want to save the content of your json to a file.
Old answer
If you want to save the changes to a file located on the server, you need to send the informations to said server, preferably via a POST request.
A simple way to do it is to use Ajax requests.
You can use the JSON.stringify method to format your users object.
xhttp.send(JSON.stringify(users));
Then you can handle the request on the server. The way to do that depends on the language used (PHP, Ruby, Node, etc)
Observations :
You are pushing a element into a local array userList. If you want to update the rolecall.json file, you'll need to write back to that file.
Javascript (client side) has not functionality to create, edit etc.. files.You can do it in back-end side.
Workaround :
You got your json in userList constant variable. now you can push that element into the array and then write back to rolecall.json if you're manipulating it in your backend (ie.: NodeJs)
const userList = {
"users": ["288381238123", "12312123123"]
};
userList.users.push('82313123');
console.log(userList);
In node.js you can use the fs library.
fs = require('fs');
fs.writeFile('fileName.json', JSON.stringify(userList));
Related
I'm working on an MVP for a project, and I'm trying to mock up a "database" quick and dirty. I thought for now I'll just put my "database" into a .json file and work with that. I am able to use iron-ajax to get a file read in to a Polymer property to be manipulated, however, I don't know how I could write it back onto the filesystem once I manipulated it. I tried
let fs = require('fs');
fs.writeFile('./db/db.json', json, 'utf8');
However, this does not work (apparently, require does not work on the client side). I've tried googling around and checking the answers on the linked thread, but the answers are quite vague ("use <script> tag" - okay, but how?) and I haven't been able to figure it out. How would I be able to pass a json object and write it back to the filesystem?
Simple answer is no you can't. You have to write a little backend for that but for that i usually use the localStorage there you can store JSON and read write.
I have been using SQL for quite a while now, for a node.js project, I wanted to make the package smaller, and easier to manage, I thought by getting rid of MYSQl I can have put the database as part of the server, using a CSV file, or or something similar, and a variable array, how could I archive this?
I am yet to try any code, but this is how I am planning on going about it at the moment:
A basic express web server using the GET/POST requests, import a CSV file to a array, then do a basic variable comparison, like say, if (vararray === "foo"){
return "foo" exists in the database.}
I am still relatively new to javascript.
I am writing a small application for my Pebble. The intent is to send web services to a server and then process the XML response. The problem here is that Pebble.JS does not support XML responses, only text or JSON responses. I am looking for a way to convert the response to JSON to easily make use of the information. I cannot find a working way for Pebble.JS to accomplish this.
Does anyone know how to get the attributes and the child elements (with its attributes) of the XML in JSON in Pebble.JS?
Thanks!
You could use a Node XML Parser like this one (https://github.com/Leonidas-from-XIV/node-xml2js) and make it compatible to a "browser" with Browserify (https://github.com/substack/node-browserify).
Browserify usage:
browserify raw-app.js -o compiled-app.js
I think you need to have nodejs installed too but this isnĀ“t a big problem.
Here some code which written on-the-fly:
var xml2js = require('xml2js');
var xml = "<root>This is a root object!<child>This a child</child></root>"
xml2js.parseString(xml, function (error, result) {
console.log(result); // JSObject
});
The issue is that jQuery Mobile does not support responses coming in as XML. I have quite annoyingly run into this issue before. The way I got around it was by creating my own JSON Object with the expected response tags in the following way:
var IDs = message.match(/<id>(.*?)<\/id>/g);
var tempID = IDs[0].replace('<id>','').replace('</id>','');
That's just a part from my actual project that I was working on this for. It will require a little bit of modifying as per your needs to get it to how you want it. You likely will want to have that second line inside a loop with some other arrays from your .match() calls, when making your JSON Object. At the end, you need to use the JSON.parse(...); function call to assign a variable the JSON addressable object you've made.
I have some set of preset values associated with a item in dropdown list. Since the list is large I don't want to store them in js file with if else block.
I found that I can store them in json format but it seems like jquery.getJson() makes http get request for this even if file is stored locally. This may add some delay in fetching values. In my case instant response is really important because these vales will be changed during realtime sound editing feature.
I was thinking may be I can load these values on page load itself and store it in some variable and then when required do if else to find particular value. Though I am not really sure if this is right way to do. Please suggest.
Have you thought of DOM storage.
Have a look at this and check it serves any of your purpose.
Well, given your requirements, You'd have to load them by including js files.
In main html, you'd have:
<script>
var GlobalData = {};
</script>
<script src="albums.js"></script>
<script src="songs.js"></script>
...
Then, in albums.js (or any other file) you'd have:
GlobalData.albums = [
//... your data here
];
Then, to access this data when you need it, just do it straightforward
alert(GlobalData.albums.length);
However, if the amount of data is big, it's better if you don't have it always in memory. You could dynamically load it or save it on localStorage.
Cheers
You mentioned jQuery, so I guess $.data will do the trick - http://api.jquery.com/data/
if im loading data for the markers from a database do i write the output queried from the db into a javascript file or is there a cleaner way of doing it?
thanks
Yeah, writing to a file is a good way to do it. Just write the data as JSON. Your file would look like:
var map = {waypoints:[...]};
And then you can do:
for(var i=o; i<map.waypoints.length; ++i) {
addWaypoint(map.waypoints[i]);
}
I actually do some static caching of nodes using this method: http://www.trailbehind.com/site_media/javascript/gen/national-parks.js
We use that set of National Parks a lot, so we cache it. But we also have urls where you can fetch JSON for a node on the fly, such as: http://www.trailbehind.com/map/node/7538973/632/735/
This URL gets the map for node 7538973, and specifies the dimensions of their map in pixels as well.
The needed Javascript can of course be wrapped in whatever language you prefer to use, see e.g. pymaps for a Python example. While pymaps is actualally inserting the JS code into an HTML template, if you're writing a web app you can perfectly well choose to serve that JS code on the fly at an appropriate URL and use that URL in a <script> tag in your pages.
Depending on the size of your application, you may want to consider printing out plain javascript.
I have a map that uses server-side clustering, so markers update frequently. I found that parsing JSON markers slowed the app significantly, and simply wasn't necessary.
If speed is an issue, I'd suggesting removing all of the unnecessary layers possible (JSON, AJAX, etc.). If it's not, you'll be just fine with JSON, which is cleaner.
I agree with Andrew's answer (+1).
I guess the only point I would add is that rather than including some server side generated JavaScript, you could use an AJAX request to grab that data. Something like:
var request = new Request.JSON (url: 'get_some_json.php',
onSuccess: function(data) {
// do stuff with the data
}).get ();
(This is a Mootools AJAX thing, but you could use any kind of AJAX request object).
Edit: ChrisB makes a good point about the performance of parsing JSON responses and re-reading my answer I certainly didn't make myself clear. I think AJAX requests are suitable for re-requesting data based on parameters generated by user interaction. I guess an example use case might be, a user filtering the data displayed on the map. You might grab the filtered data via an AJAX/SJON request rather than re-loading the page.