skip to Main Content

I am using Python. I need to gather the content of js object while maintaining the values’ type.

for example I have a js file with the next content

const rules = {
    force_update_cache: true,
    country: 'gb',
    override_headers: {
      'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1',
    },
    navigate_opt: {wait_until: ['domcontentloaded'], timeout: 60*SEC},
}

I want to extract the keys and values of rules while maintaining the original type of the values.

I regexed my way to read only the keys and values without the "const rules {, }".
I tried using ast.literal_eval but it doesn’t work propely.

I expect to get evantually a dictionary with the keys, and values with their original type.

string.
number.
integer.
object.
array.
boolean.
null.

Is there a solution for that?

2

Answers


  1. use the vm module in Node.js to execute the JavaScript code and access the resulting object.

    const vm = require('vm');
    
    const script = `
    const rules = {
    force_update_cache: true,
    country: 'gb',
    override_headers: {
    'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) 
    AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 
    Safari/602.1',
    },
    navigate_opt: {wait_until: ['domcontentloaded'], timeout: 60*SEC},
    };
    
    rules;
    `;
    
    const sandbox = { SEC: 1 }; // Define any variables needed in the code
    
    const context = vm.createContext(sandbox);
    const result = vm.runInContext(script, context);
    
    console.log(result);
    
    Login or Signup to reply.
  2. maybe you can try this

    const rules = {
      force_update_cache: true,
      country: 'gb',
      override_headers: {
        'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1',
      },
      navigate_opt: {wait_until: ['domcontentloaded'], timeout: 60*SEC},
    };
    
    // Convert the object to a string
    const rulesString = JSON.stringify(rules);
    
    // Remove the surrounding braces to get the object literal
    const objectLiteral = rulesString.slice(1, -1);
    
    // Use eval() to parse the object literal
    const parsedObject = eval('(' + objectLiteral + ')');
    
    console.log(parsedObject);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search