How to replace values ​​from JSON with RegEx found in a file using Python?

Suppose there is a file in the file system that contains the values ​​that are prefixed $.

eg.

<ul>
    <li>Name: $name01</li>
    <li>Age: $age01</li>
</ul>

I can get the values ​​through RegEx:

#!/usr/bin/env python 
import re

with open("person.html", "r") as html_file:
    data=html_file.read()   
list_of_strings = re.findall(r'\$[A-Za-z]+[A-Za-z0-9]*', data)
print list_of_strings

This lists the values:

[$name01, $age01]

Now I send the payload to the JSON sample to my web.py server as follows:

curl -H "Content-Type: application/json" -X POST -d '{"name":"Joe", "age":"25"}' http://localhost:8080/myservice

I can get these values ​​as follows:

import re
import web
import json

urls = (
    '/myservice', 'Index',
)

class Index:
    def POST(self):
        data = json.loads(web.data())

        # Obtain JSON values based on specific keys
        name = data["name"]
        age = data["age"]

Question (s):

  • How can I get JSON values ​​from the payload iteratively and put them in a list (instead of manually retrieving them by key name)?

  • Once I have this list, how can I replace the values ​​in the HTML file with the JSON values ​​in the list?

eg.

How to manually insert these elements into an HTML file (according to ExExExExEx, which was defined above):

Replace $ name01 with a name?

<ul>
    <li>Name: Joe</li>
    <li>Age: 25</li>
</ul>
+4
2

,

, , , .

( - json-):

def replace_all(output_file, data):
    homedir = os.path.expanduser("~")
    contracts_dir = homedir + "/tmp"
    with open(output_file, "r") as my_file:
        contents = my_file.read()
    destination_file = contracts_dir + "/" + data["filename"]
    fp = open(destination_file, "w")
    for key, value in data.iteritems():
        contents = contents.replace("$" + str(key), value)
    fp.write(contents)
    fp.close()
+1

( , ):

import re
import json

html = """
<ul>
    <li>Name: $name01</li>
    <li>Age: $age01</li>
</ul>"""

JSON = '{"name01":"Joe", "age01":"25"}'
data = json.loads(JSON)

html = re.sub(r'\$(\w+)', lambda m: data[m.group(1)], html)

print(html)

:

<ul>
    <li>Name: Joe</li>
    <li>Age: 25</li>
</ul>

, Template, Jinja2. web.py, . : http://webpy.org/docs/0.3/templetor

+1

Source: https://habr.com/ru/post/1616657/


All Articles