Tom
Tom

Reputation: 1291

extract the value of an array in an existing javascript file

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.

Upvotes: 0

Views: 1009

Answers (1)

jfriend00
jfriend00

Reputation: 707288

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.

Upvotes: 1

Related Questions