Python script that reads a Json and converts to a javascript

Asked

Viewed 104 times

-1

Hello I would like a help,

I have a json that I can pick up from the web or download into my linux... and I need to build a standard code from this json.

I need to mount an always standard javascript with the modifications coming from my json.

I need to change two values in my javascript.

Today it works right, but I mount manual, I wanted to mount it automatically using python or javascript.

My Json :

{
    "home": [
        {
            "base_url": "home",
            "redirect_url": "/",
            "type": "www.testemestradoolpt.com.br"
        }
    ],
    "portal": [
        {
            "base_url": "portal",
            "redirect_url": "/",
            "type": "www.testemestradoolpt.com.br"
        }
    ],
    "digital": [
        {
            "base_url": "digital",
            "redirect_url": "/",
            "type": "www.testemestradoolpt.com.br"
        }

    ]
}

My Javascript:

'use strict';

const querystring = require('querystring');

 exports.handler = (event, context, callback) => {
     const request = event.Records[0].cf.request;
     const headers = request.headers;
     const uri = request.uri;

     var origin = request.origin[0].custom.domainName;
     console.log(`Request #PATH# is "${uri}"`);
     console.log(`Request #INCOMING REQUEST ORIGIN# set to "${origin}"`);
    
     const regex = /^\/(digital|home|portal|)[^\/]*/i;  **<<<< ADICIONAR AQUI**
     if (regex.test(request.uri))
     {
             /* Set custom origin fields*/
             request.origin = {
                 custom: {
                     domainName: 'www.testemestradoolpt.com.br' **<< ADICIONAR AQUI**
                 }
             };
             request.headers['host'] = [{ key: 'host', value: '*'}];
             /**origin = request.origin.custom.domainName;  enable it for testing*/
    }
    /** for testing purposes don't use unless you need to, big performance hit
    console.log(`###### - > Request HOST "${request.headers.host[0].value}"`);
    console.log(`###### - > Final Request Origin Server "${origin}"`);
    */
    callback(null, request);
};

If you notice I just need to add my base_url that comes from my json in the javascript regular expression field and only once the type that and the url in the other field, the url will always be the same.

I made a script in python that brings me the base url, but I need a script in python that mounts to min the javascript with the variables of json as the java script above I sent, and I’m having a lot of difficulty in doing this, follow what I managed to do in python:

import json

with open('dataload.json') as json_file:
    data = json.load(json_file)
    for p in data ['home']:
         print(p['base_url'])

1 answer

0


You can do something like:

regexp = []
url = ''
for key in json:
    for value in json.get(key, []):
        url = value.get('type')
        regexp.append(value.get('base_url'))

regexp = str('|').join(regexp)

js_script = """
'use strict';

const querystring = require('querystring');

 exports.handler = (event, context, callback) => {
     const request = event.Records[0].cf.request;
     const headers = request.headers;
     const uri = request.uri;

     var origin = request.origin[0].custom.domainName;
     console.log(`Request #PATH# is "${uri}"`);
     console.log(`Request #INCOMING REQUEST ORIGIN# set to "${origin}"`);

     const regex = /^\/(""" +  regexp + """|)[^\/]*/i;  **<<<< ADICIONAR AQUI**
     if (regex.test(request.uri))
     {
             /* Set custom origin fields*/
             request.origin = {
                 custom: {
                     domainName: '""" +  url + """' **<< ADICIONAR AQUI**
                 }
             };
             request.headers['host'] = [{ key: 'host', value: '*'}];
             /**origin = request.origin.custom.domainName;  enable it for testing*/
    }
    /** for testing purposes don't use unless you need to, big performance hit
    console.log(`###### - > Request HOST "${request.headers.host[0].value}"`);
    console.log(`###### - > Final Request Origin Server "${origin}"`);
    */
    callback(null, request);
};
"""

# salvar o arquivo
# ou responder a requisição http com esse script.

You can create a route on your server that generates and returns this file to the client.

in the client (html file) you can do something like:

<script src="rota/que/retorna/o/script/gerado/dinamicamente"></script>

I don’t know which framework you’re using, but don’t forget to define the content-type Answer header us as text/javascript.

  • A query in the url field"" I put the url of my json? I ran and the following error appeared. root@LAPTOP-3IP5GPAG:~/Cdn/python# python python2.py Traceback (Most recent call last): File "python2.py", line 3, in <module> for key in json: Nameerror: 'json' is not defined name

  • in line 3 it iterates the variable json that you have to exchange/or define it with your json.

  • Problem Solved. Thanks man!

  • But you can help me... it seems that the topic can not post more doubts... I will edit the question.

  • I asked this new question here: https://answall.com/questions/419111/problems-to-do

Browser other questions tagged

You are not signed in. Login or sign up in order to post.