Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable to JSON, for python?

Tags:

python

json

I am new in work with JSON, so sorry in advance for the stupid question.

I want to write JSON with the variable in the value field. It looks like this:

def print_json(user_name):
    opened_json = open('way/to/json/file')
    tmp = json.load(opened_json)

    res = tmp(['path_to_folder'](user_name))
    print(res)

def main(user_name):
    print_json(user_name)


main('user')

It is JSON:

{"path_to_folder": "/Users/" + user_name + "/my_folder/"}

Awaiting for that output:

/Users/user/my_folder/

Please, tell me if any solution here exists.

Thanks in advance!

EDIT: My problem, that I can't add variable to JSON correctly. It marked red. Wrong syntax, when I try to concat.

like image 266
Vas23Vewe Avatar asked Jun 04 '20 12:06

Vas23Vewe


People also ask

How do you pass a variable into a JSON body in Python?

Try using r = s. post(url, data=payload, auth=('test01', 'test01')) as the last line. If that doesn't work try r = s. post(url, json=payload, auth=('test01', 'test01')) .

How do you input a JSON in Python?

It's pretty easy to load a JSON object in Python. Python has a built-in package called json, which can be used to work with JSON data. It's done by using the JSON module, which provides us with a lot of methods which among loads() and load() methods are gonna help us to read the JSON file.


1 Answers

What you want isn't directly possible in JSON, because it doesn't support "templating".

One solution would be to use a templating language such as Jinja to write a JSON template, then load this file without the json library and fill in the values using Jinja, and finally use json.loads to load a dictionary from your rendered string.

Your json-like file could look something like this:

{"path_to_folder": "/Users/{{ user_name }}/my_folder/"}

Your Python code:

import json
from jinja2 import Environment, FileSystemLoader

env = Environment(
    FileSystemLoader("path/to/template")
)
template = env.get_template("template_filename.json")

def print_json(username):
    return json.loads(
        template.render(user_name=username)
    )
...

In fact, if this is a simple one-time thing, it might even be better to use Python's built-in templating. I would recommend old-style formatting in the case of JSON, because otherwise you'll have to escape a lot of braces:

JSON file:

{"path_to_folder": "/Users/%(user_name)s/my_folder/"}

"Rendering":

with open("path/to/json") as f:
    rendered = json.loads(f.read() % {"user_name": username})
like image 158
L3viathan Avatar answered Nov 06 '22 10:11

L3viathan