Reading JavaScript variables from a file using Python

I use some server side Python scripts to compile JavaScript files into a single file, and also add information about these files to the database. To add information about the scripts, I now have a yaml file for each js file with some information inside it that looks like this:

title: Script title
alias: script_alias

I would like to throw away yaml, which seems redundant for me, if I can read these variables directly from JavaScript, which I could place at the very beginning of the file as follows:

var title = "Script title";
var alias = "script_alias";

Is it easy to read these variables using Python?

+3
source share
2 answers

Assuming you only need 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
+4

JSON? , javascript, python .

+2

All Articles