Sergei Basharov
Sergei Basharov

Reputation: 53850

Read JavaScript variables from a file with Python

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?

Upvotes: 3

Views: 12754

Answers (2)

sberry
sberry

Reputation: 132018

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

Upvotes: 4

matzahboy
matzahboy

Reputation: 3024

Have you tried storing the variables in a JSON format? Then, both javascript and python can easily parse the data and get the variables.

Upvotes: 2

Related Questions