extract the value of an array in an existing javascript file - javascript

I'm trying to convert values defined in a javascript file to a json file or extract those values to some other format that I can process with python. Does anyone know of a python library, node.js package or other method for doing this with a local file? I cannot use ajax or php for this task.
Context:
I have a javascript file called file.js, in which there are no functions, but a number of lengthy arrays defined in the following fashion:
var an_array1 = new Array();
an_array[1] = {some array values 1}
...
an_array[n] = {some array values n}
var another_array = new Array();
another_array[1] = {some other array values 1}
...
another_array[m] = {some other array values m}
No functions are included in this file, just the calls to var and the subsequent setting of the array values.
Similar questions provide answers that focus around using ajax or php, but I do not think I can use these tools for this purpose. I can, however, use node.js, python and any associated libraries/packages. I would also be game to try an awk/sed type script, but I don't think this will work here, since the data I want requires file.js to be parsed/processed first.
Ideal outcome
Ultimately, I'd like to use some method to process the file.js, extract the value of one particular array to its own file as JSON, or some other, similar format (XML would be fine too, even csv would work). e.g.:
file.json:
[{some array values 1},...,{some array values n}]
Does anyone know how this might be done? There are some questions similar to this, but those assume that I am querying a website or something, which is not the case here.

Here's a node file that could do this for you if the file.js file is structured to declare the desired variables at the top level. If that isn't the case, you will have to show us what exactly file.js looks like.
// load filesystem module
var fs = require("fs");
// read JS file and execute it
var data = fs.readFileSync("file.js", {encoding: "utf8"});
eval(data);
// write data out to files
fs.writeFile("result1.json", JSON.stringify(an_array1));
fs.writeFile("result2.json", JSON.stringify(an_array2));
You would then just run this JS file with node.js.
This would use the V8 JS interpreter in node to parse the JS file with your variables in it. It would then load the file system module and then write the JSON representation of two separate arrays out to files.
You can then write Python to read those files, parse the JSON into a form Python understands (Python has JSON parsing built-in) and then do whatever you want with the data in Python.

Related

How do I HTTP GET a .js file and extract 'exports' variables?

I am writing a site in Laravel to complement a game written in Node. It pulls information directly from the game's .js files stored on GitHub and the plan is to use Vue to generate some nice HTML to display the data.
The .js files are of the form:
'use strict'
let x = {...};
exports.x = x;
I can import the files using a PHP request (simply using 'file') and pass them to JS with either jQuery.getScript or axios.get (so far). However, I am having real trouble coming up with a way to extract the 'x' values here under exports. If I were writing a JS app in node, I would simply do the following:
var xFile = require('xFile');
var x = xFile.x;
However, I can't figure out how to do that here as both GET methods return a string, not a JS file. JSON.parse() doesn't work, and I would like to come up with a solution that doesn't just replace the non-JSON text as I would need a reusable solution for other files. I don't suppose anybody has any ideas?
Thanks so much!
You could try something like below.
you could create the script tag dynamically and attach the script in the body and add your javascript code using innerHTML.
You call this script in your ajax response code.
let script = document.createElement('script');
script.innerHTML = 'alert("Hi")';
document.querySelector('body').appendChild(script);
I managed to figure it out! It's a little janky, but you can run a node file in PHP with the exec command. I just wrote a node file to import the file and return the useful data. This probably isn't an optimal solution, but it works for me since I'm much more confident with JS than with PHP.

Pushing to an array in a separate JSON file

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

Reverse a Javascript Build

I have a javascript build file, that is unminified; it contains prototype class definitions. Is there any tool i can use to break the build file into separate files, assuming one file per prototype/class definition?
This build file looks like the following, with many objects defined in the following way, all concatenated into the single file. I would like to break this file apart. I don't have access to the original source code, I was basically just given a dump in the form of this build file but its unmanageable in this form as its 10k+ lines of code.
MyClass = function(){
}
MyClass.prototype.foo = function(){
}
I would go with the suggested (in comments) do it manually manner, but if you insist to automate it some way, you can always use javaScript for the job.
One way would be to look up for constructors throw a regex like ([^\.=\s]+[^=]*=[\s]*function[\s]*[(]+[^)]*[)][\s]*[{]*) and extract all 'class'.prototype.'something' from the file, parse the entire file then write each group in separate files after doing any kind of ordering you would prefer.
Another manner would be to use a javaScript parser and group relevant function definitions throw token examination (this one is overkill, but might be interesting for learning purposes).

Convert XML to JSON with pebble.js

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.

Is it possible to read values from a JSON object stored in another javascript file?

I am working on a custom piece where I am dynamically building very specific tables and writing them out using javascript after an AJAX call. I am trying to avoid writing custom code for each of these tables by coming up with a standard layout where I customize the layout via values in a JSON object stored in my current javascript file. Is there anyway I can store this object in another file and read it as if it were a properties file to make things neater?
Javascript stored in separate files can be referenced as long as it is not wrapped somehow in a function, if so then you would need to reference that function. Thus JSON objects stored in separate files can be referenced - they are just Javascript (everything is an object in Javascript).
SO if you have simple object, or complex JSON:
myobject = "fred";
myobject2 = "wilma";
They can still be referenced, if they are in the same file, or not.
alert(myobject + myobject2);
shows "fredwilma"
Of course JSON objects would be more complicated, but the principle still applies.
You need to dynamically load your additional javascript files. Here is a good article that portrays how to do that using static / dhtml methods.
Like m_oLogin said, you can dynamically load the additional scripts. Instead of doing as the article suggested, you can also use jquery to load the scripts -
$.getScript('script/loaded-script.js'), function() {
//action to execute after script is loaded
});

Categories