Skip to content
Advertisement

Inserting values into JS scripts using python

I am parsing JS files stored in a directory to fetch out the values inside tags. Upon finding relevant values in the tags using regex, I want to move those values under a new section called controls. I have been able to get the required values in the controls variable using the script below:

JavaScript

I am not able to think of a way to now insert the controls list as a new field into the JS file and update it. It should appear after the tags field.

An example JS file looks like:

JavaScript

My end goal is to create a JS file whose tags and newly added controls section looks like this:

JavaScript

Edit: Able to get it working with the solution provided by @Dan-Dev. The only thing which is still out of place is the closing ]. Is there a way to fix the closing bracket to indent correctly?

JavaScript

Advertisement

Answer

You can extract the tags and convert them to JSON using the package jsonnet iterate over them using your regex then build a string to replace the original tags like this:

JavaScript

Outputs:

JavaScript

UPDATED WITH FORMATTING:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement