Read JavaScript variables from a file with Python - javascript

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.

Related

How to get file extension from file content using Node.js

I need some help. I need to fetch what the file type should be from the file containing only using Node.js. I am explaining the scenario below.
Let's say I have some content like below.
let fileContent = "The textContent property sets or returns the text content of the specified node, and all its descendants."
As we can see here the variable fileContent has some text data and I want to write this data into one file. So for that, I need to create the file with a proper extension like abc.txt. Similarly, If fileContent has some json data then I will create the file like abc.json and write the value inside it.
So here I need to fetch what should be the type of file from this content only using Node.js. If anybody has a solution for this will be a great help.
You can use popular file-type package for this. You can send buffer/file/stream/blob as an input and get file type as an output.
const FileType = require('file-type');
...
const { ext, mime } = await FileType.fromBuffer(your_data);

Reading an Exported Javascript Object in Python

Is it possible to read/parse an exported Javascript or Typescript JSON-like object in Python?
For example:
In myJava.js:
export const myObj = {
entry: val
entry2: val2
...
}
In parseJava.py:
def parseJava():
# Some code to read in the javascript object
javaObjAsDictionary = someFunction("myJava.js")
Does such a "someFunction()" exist? If not, are there any clean ways around this?
Thanks in advance!
If you want to parse JSON, there is a library called JSON in Python 2 and 3 that does the encoding and decoding.
Specifically, you can use the json.loads or json.load methods to get a Python object (dictionary/list) from your JSON.
Something like:
import json
jsonDict = json.load("myJSON.json")
I am not sure exactly if this is what you need, hope this gives you a start.
# following code assumes that 'data.json' file exists in the current working directory
with open('data.json', 'r') as jsonFile: # opens JSON file in read only mode
# loads the content of JSON file and converts it into python dictionary object
dictionary = json.load(jsonFile)
print(dictionary)

Getting Variables from a external .json file Python

What I need help with
I want to receive variables from a external .json file in the local directory
using python27
(import doesn't work)
I want to store the variables in the .json like below
value1 = "this_is_value1"
value2 = "this_is_value2"
value3 = "this_is_value3"
and have them being used in a script.
If I can get it to the point of which the .json includes
value1 = "this_is_value1"
and my .py includes
print(value1)
with output
>>>this_is_value1
I can take it from there
My end Task
The idea is that I need to change specific parts of another .yaml file, this program needs to take variables like (ID, System_id, IP) and for this case I need a .json I can change which the python27 script then pulls the information from to change the .yaml file.
I've done this part fine, just need to do this part
Have I researched the issue?
In short, YES.
however, theses answer use .py or other file types.
I've already tried importing the file but since it needs to sit next to the script I can't use import
Other anwser simply give no information back about how they solved the issue.
With a json formatted file (say "my_file.json"), for instance:
{
"x": "this is x",
"y": "this is x",
"z": "this is z"
}
Then in Python:
import json
with open("my_file.json", "r") as f:
my_dict = json.load(f)
print(my_dict["x"])
Yields:
this is x
I generally like to control this process with a method or function. Here is a code snip I use frequently that will read the format of the text file you've shown:
class MainApp(object):
def __init__(self, config_file):
# Initialization stuff from a configuration file.
self.readConfigFile(config_file)
def readConfigFile(self, file):
try:
with open(file, 'r') as cfg:
lines = list(cfg)
print("Read", len(lines), "lines from file", file)
# Set configured attributes in the application
for line in lines:
key, value = line.split('=')
setattr(self, key.strip(), value.strip())
except:
print('Configuration file read error')
raise
if __name__ == '__main__':
# Create an instance of the application.
# It will read the configuration file provided here.
app = MainApp('myconfig.txt')
# Now you can access the attributes of the class (read from config file)
print(app.value1, app.value2, app.value3)
This should work:
>> string1 = 'value1 = "this_is_value1"'
>> exec(string1)
>> print(value1)
"this_is_value1"
If what you really need is a .txt file, then I recommend you to take a look at the documentation:
https://docs.python.org/3/tutorial/inputoutput.html
Go to section: 7.2 Reading and Writing a file
Basically, you'll need is:
lines = [] # for further data manipulation
file = open("c:\path\to\your.txt", "r")
for line in file:
lines.append([line.split("=")])
file.close()
Now if you have in your .txt bar="foo"
Then in the lines list you can do:
lines[0][0] # output "bar"
lines[0][1] # output "foo"
Of course there are some more smater way of doing this, but this is just basic idea.

Insert object data into JSON file

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

Import JSON with mongo script

I'm trying to write a mongo script to import a jsonArray from a JSON file. My script is in .js format and I execute it with load() command in mongo shell. Is it possible to do it with a mongo script?
I know I can use mongoimport instead. But I want to know a way to do it with a script.
The contents of my current script in which the import part is missing is given below..
var db = connect("localhost:27017/fypgui");
//Import json to "crimes" collection here
var crimes = db.crimes.find();
while (crimes.hasNext()){
var item = crimes.next();
var year =(item.crime_date != null)?(new Date(item.crime_date)).getFullYear():null;
db.crimes.update( {_id: item._id}, {$set: {crime_year: year}});
}
There is another answer to this question. Even though it's a bit old I am going to respond.
It is possible to do this with the mongo shell.
You can convert your JSON to valid JavaScript by prefixing it with var myData= then use the load() command to load the JavaScript. After the load() you will be able to access your data from within your mongo script via the myData object.
data.js
var myData=
[
{
"letter" : "A"
},
{
"letter" : "B"
},
{
"letter" : "C"
}
]
read.js
#!/usr/bin/mongo --quiet
// read data
load('data.js');
// display letters
for (i in myData) {
var doc = myData[i];
print(doc.letter);
}
For writing JSON is easiest to just load your result into a single object. Initialize the object at the beginning with var result={} and then use printjson() at the end to output. Use standard redirection to output the data to a file.
write.js
#!/usr/bin/mongo --quiet
var result=[];
// read data from collection etc...
for (var i=65; i<91; i++) {
result.push({letter: String.fromCharCode(i)});
}
// output
print("var myData=");
printjson(result);
The shebang lines (#!) will work on a Unix type operating system (Linux or MacOs) they should also work on Windows with Cygwin.
It is possible to get file content as text using undocumented cat() function from the mongo shell:
var text = cat(filename);
If you are interested cat() and other undocumented utilities such as writeFile are defined in this file: shell_utils_extended.cpp
Having file's content you can modify it as you wish or directly pass it to JSON.parse to get JavaScript object:
jsObj = JSON.parse(text);
But be careful: unfortunately JSON.parse is not an equivalent of mongoimport tool in the sense of its JSON parsing abilities.
mongoimport is able to parse Mongo's extended JSON in canonical format. (Canonical format files are created by bsondump and mongodump for example. For more info on JSON formats see MongoDB extended JSON).
JSON.parse does not support canonical JSON format. It will read canonical format input and will return JavaScript object but extended data type info present in canonical format JSON will be ignored.
No, the mongo shell doesn't have the capability to read and write from files like a fully-fledged programming environment. Use mongoimport, or write the script in a language with an official driver. Node.js will have syntax very close to the mongo shell, although Node.js is an async/event-driven programming environment. Python/PyMongo will be similar and easy to learn if you don't want to deal with structuring the logic to use callbacks.
Hey I know this is not relevent but, every time I need to import some jsons to my mongo db I do some shity copy, paste and run, until I had enough!!!
If you suffer the same I v written a tiny batch script that does that for me. Intrested?
https://github.com/aminjellali/batch/blob/master/mongoImporter.bat
#echo off
title = Mongo Data Base importing tool
goto :main
:import_collection
echo importing %~2
set file_name=%~2
set removed_json=%file_name:.json=%
mongoimport --db %~1 --collection %removed_json% --file %~2
goto :eof
:loop_over_files_in_current_dir
for /f %%c in ('dir /b *.json') do call :import_collection %~1 %%c
goto :eof
:main
IF [%1]==[] (
ECHO FATAL ERROR: Please specify a data base name
goto :eof
) ELSE (
ECHO #author amin.jellali
ECHO #email a.j.amin.jellali#gmail.com
echo starting import...
call :loop_over_files_in_current_dir %~1
echo import done...
echo hope you enjoyed me
)
goto :eof

Categories

Resources