1

I have a Python3 script that takes an input HTML template and populates some data using this JSON and creates an output HTML.

Python Script -

with open('./jsonInp.json') as jsonFile:
    jsonData = json.load(jsonFile)

inp_f = open('brandedTemplate.html', 'r+')
htmlInp = inp_f.read().format(links = jsonData['links'])

My JSON File -

{
    "links" : {
        "one" : "www.one.com",
        "two" : "www.two.com",
    } 
}

Now using this in the input HTML like :

...
<a href={links.one}></a>
...

But this doesn't work. Neither does links['one'].

The JSON loading and everything works fine. I am also able to use arrays from .format function. Just can't find how to use this object anywhere. From type(jsonData['links']), I know its a Python dict.

Is there a way to use this in a html template?

4
  • 1
    if you try <a href={jsonData['links']['one']}> ? Commented Apr 23, 2018 at 15:38
  • 1
    Almost: remove the apostrophe: <a href={jsonData[links][one]}> Commented Apr 23, 2018 at 15:43
  • Shoot... The apostrophe thing worked. Thanks @Jeronimo Commented Apr 23, 2018 at 15:46
  • @Jeronimo: Oh yes, I slipped on the apostrophes ;-) Thanks Commented Apr 23, 2018 at 15:50

2 Answers 2

1

Your jsonData variable is a python dict. To access values in the format mini language you need to use {my_dict[my_key]}. Note that the key is not enclosed in quotes. To fix your example, the html input should be as follow:

...
<a href={links[one]}></a>
...
Sign up to request clarification or add additional context in comments.

Comments

0

According to [Python]: Format examples, you should use (templates like):

<a href={links[one]}></a>

as html format specifier (since [Python]: json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) returns a dict).

Example:

>>> json_dict
{'links': {'one': 'www.one.com', 'two': 'www.two.com'}}
>>> href_text
'<a href={links[one]}></a>'
>>> href_text.format(links=json_dict["links"])
'<a href=www.one.com></a>'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.