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.
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')) .
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.
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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With