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:

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

Your Python code:

Copyimport 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:

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

"Rendering":

Copywith open("path/to/json") as f:
    rendered = json.loads(f.read() % {"user_name": username})
Answer from L3viathan on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › pass-by-assignment-in-python
Pass by Assignment in Python - GeeksforGeeks
July 23, 2025 - In Python, pass-by-assignment refers to the way function arguments are passed. This means that when a variable is passed to a function, what gets passed is a reference to the object in memory, not the actual object itself.
Discussions

arrays - sending json object to function python - Stack Overflow
I know it isn't possible to pass a JSON object directly to another function · There is no "JSON object" you have a python list that contains a python dictionary. More on stackoverflow.com
🌐 stackoverflow.com
python - what does it mean by 'passed by assignment'? - Stack Overflow
Whenever a value gets assigned ... it's an assignment statement, a function call, an as clause, or a loop iteration variable, there's just one set of rules. But overall, your intuitive idea that Python is like Java but with only reference types is accurate: You always "pass a reference by ... More on stackoverflow.com
🌐 stackoverflow.com
How to use a json object as parameters to a python function.
Firstly, please stop calling this a "JSON object". It's not, it's a Python dictionary. Secondly, what are you trying to achieve? What will the function do with those args? You can always convert a dict into keyword arguments by using the ** syntax - f(**obj) - but I don't understand how the function is supposed to work if it's not already expecting arbitrary keywords. More on reddit.com
🌐 r/learnpython
7
4
November 14, 2023
How to assign variables using JSON data in python - Stack Overflow
If you feel like MySQL is too complex for your needs, may I suggest SQLite? It's supported out of the box in Python, there's no server process (just a file) and you get all the database features that JSON does not provide by itself. More on stackoverflow.com
🌐 stackoverflow.com
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
Top answer
1 of 2
24

tl;dr: You're right that Python's semantics are essentially Java's semantics, without any primitive types.


"Passed by assignment" is actually making a different distinction than the one you're asking about.1 The idea is that argument passing to functions (and other callables) works exactly the same way assignment works.

Consider:

def f(x):
    pass
a = 3
b = a
f(a)

b = a means that the target b, in this case a name in the global namespace, becomes a reference to whatever value a references.

f(a) means that the target x, in this case a name in the local namespace of the frame built to execute f, becomes a reference to whatever value a references.

The semantics are identical. Whenever a value gets assigned to a target (which isn't always a simple name—e.g., think lst[0] = a or spam.eggs = a), it follows the same set of assignment rules—whether it's an assignment statement, a function call, an as clause, or a loop iteration variable, there's just one set of rules.


But overall, your intuitive idea that Python is like Java but with only reference types is accurate: You always "pass a reference by value".

Arguing over whether that counts as "pass by reference" or "pass by value" is pointless. Trying to come up with a new unambiguous name for it that nobody will argue about is even more pointless. Liskov invented the term "call by object" three decades ago, and if that never caught on, anything someone comes up with today isn't likely to do any better.

You understand the actual semantics, and that's what matters.


And yes, this means there is no copying. In Java, only primitive values are copied, and Python doesn't have primitive values, so nothing is copied.

the only difference is that 'primitive types'(for example, numbers) are not copied, but simply taken as objects

It's much better to see this as "the only difference is that there are no 'primitive types' (not even simple numbers)", just as you said at the start.


It's also worth asking why Python has no primitive types—or why Java does.2

Making everything "boxed" can be very slow. Adding 2 + 3 in Python means dereferencing the 2 and 3 objects, getting the native values out of them, adding them together, and wrapping the result up in a new 5 object (or looking it up in a table because you already have an existing 5 object). That's a lot more work than just adding two ints.3

While a good JIT like Hotspot—or like PyPy for Python—can often automatically do those optimizations, sometimes "often" isn't good enough. That's why Java has native types: to let you manually optimize things in those cases.

Python, instead, relies on third-party libraries like Numpy, which let you pay the boxing costs just once for a whole array, instead of once per element. Which keeps the language simpler, but at the cost of needing Numpy.4


1. As far as I know, "passed by assignment" appears a couple times in the FAQs, but is not actually used in the reference docs or glossary. The reference docs already lean toward intuitive over rigorous, but the FAQ, like the tutorial, goes much further in that direction. So, asking what a term in the FAQ means, beyond the intuitive idea it's trying to get across, may not be a meaningful question in the first place.

2. I'm going to ignore the issue of Java's lack of operator overloading here. There's no reason they couldn't include special language rules for a handful of core classes, even if they didn't let you do the same thing with your own classes—e.g., Go does exactly that for things like range, and people rarely complain.

3. … or even than looping over two arrays of 30-bit digits, which is what Python actually does. The cost of working on unlimited-size "bigints" is tiny compared to the cost of boxing, so Python just always pays that extra, barely-noticeable cost. Python 2 did, like Java, have separate fixed and bigint types, but a couple decades of experience showed that it wasn't getting any performance benefits out of the extra complexity.

4. The implementation of Numpy is of course far from simple. But using it is pretty simple, and a lot more people need to use Numpy than need to write Numpy, so that turns out to be a pretty decent tradeoff.

2 of 2
1

Similar to passing reference types by value in C#.

Docs: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-reference-type-parameters#passing-reference-types-by-value

Code demo:

# mutable object
l = [9, 8, 7]


def createNewList(l1: list):
    # l1+[0] will create a new list object, the reference address of the local variable l1 is changed without affecting the variable l
    l1 = l1+[0]


def changeList(l1: list):
    # Add an element to the end of the list, because l1 and l refer to the same object, so l will also change
    l1.append(0)


print(l)
createNewList(l)
print(l)
changeList(l)
print(l)

# immutable object
num = 9


def changeValue(val: int):
    # int is an immutable type, and changing the val makes the val point to the new object 8, 
    # it's not change the num value
    val = 8

print(num)
changeValue(num)
print(num)
🌐
Reddit
reddit.com › r/learnpython › how to use a json object as parameters to a python function.
r/learnpython on Reddit: How to use a json object as parameters to a python function.
November 14, 2023 -

Hi there, I'm learning python and I don't know how to do the following, or even if it's possible.I have a json object obj = { 'one': 1, 'two': 2 }, and a python function f(). The goal is to have the json object used as the parameters for the function, like this: f(one=1, two=2).For this example that's fine, but the problem is that the json keys are not always the same, and if my json object is obj={'cat': 'purr', 'dog': 'bark'}, the function would be called with f(cat='purr', dog='bark').If the json obj is {'first', '1st', 'second':'2nd', 'third':'3rd'}, the function would be called with f(first='1st', second='2nd', third='3rd').

The function is from a library, and for me to rewrite it to accept kwargs would imply overriding all the functions in the library (since i will be using pretty much all the functions from the library).

Is there a way to do this without overriding all the functions from the library?

Thank you in advance.

Top answer
1 of 2
5
Firstly, please stop calling this a "JSON object". It's not, it's a Python dictionary. Secondly, what are you trying to achieve? What will the function do with those args? You can always convert a dict into keyword arguments by using the ** syntax - f(**obj) - but I don't understand how the function is supposed to work if it's not already expecting arbitrary keywords.
2 of 2
1
There's no such thing as a "JSON object." JSON is a string representation format of objects, so the only thing you can be said to have that is "JSON" is a string. Otherwise what you have is a dictionary or list; a native value in Python that you might, or might not, serialize out of Python into a JSON format. But if you bring JSON into Python, it's not JSON anything. It's a plain-old dictionary or list. For this example that's fine, but the problem is that the json keys are not always the same, and if my json object is obj={'cat': 'purr', 'dog': 'bark'}, the function would be called with f(cat='purr', dog='bark').If the json obj is {'first', '1st', 'second':'2nd', 'third':'3rd'}, the function would be called with f(first='1st', second='2nd', third='3rd'). Ok, then how do you want it to work? If f needs keyword arguments like one and two, those have to come from somewhere. Conversely if you want to bind the keys of a dictionary to the parameters of a function, the function has to have those parameters. If you just want the function to accept variadic keywords, then use the double-splat operator: def f(**kwargs) and then the parameter kwargs is whatever keyword arguments were provided by the function call. It's symmetrical with dictionary unpacking in the function call - it's conceptually the opposite, packing up the keyword arguments into a dictionary - so the operator is the same (**.)
🌐
TutorialsPoint
tutorialspoint.com › article › How-to-pass-a-json-object-as-a-parameter-to-a-python-function
How to pass a json object as a parameter to a python function?
May 7, 2025 - We can pass a JSON object as a parameter to a Python function using the json.loads() method. we can also convert the JSON string into a Python dictionary or list, which depends on its structure.
🌐
Real Python
realpython.com › lessons › pass-by-assignment
Pass by Assignment (Video) – Real Python
00:12 Python doesn’t use either pass by value or pass by reference. It uses something called pass by assignment.
Published   September 21, 2021
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 61621641 › how-to-assign-variables-using-json-data-in-python
How to assign variables using JSON data in python - Stack Overflow
If you want to assign the data just use: variable1 = item["inspecteur1"]. One issue with your JSON code above is that it will print Not Found for every record that does NOT match which I don't think it's what you want.
Top answer
1 of 1
2

This depends a lot on your security goals, and on what kind of user interface you want to offer to the author of these expressions.

Loading variables into the local scope does work, since Python is a very dynamic language. There's a risk though that the variables might re-define existing objects, thus breaking your code – what if there's a variable called len, for example?

Therefore, it's usually safer to avoid running the user input in a Python context. Instead:

  • define a simple programming language for these expressions
  • write an interpreter that executes the expressions

Python does have tools to help here. We can parse strings as Python code via the ast module. This returns a data structure that represents the syntax, and doesn't execute anything (though the parser isn't necessarily safe against malicious inputs). We can take the data structure, walk it, and execute it according to the rules we define – such as by resolving variables only from a dictionary. Example code for Python 3.10:

import ast

def interpret(code: str, variables: dict) -> dict:
  module: ast.Module = ast.parse(code, mode='exec')
  for statement in module.body:
    _interpret_statement(statement, variables)
  return variables

def _interpret_statement(statement: ast.stmt, variables: dict) -> None:
  match statement:
    case ast.Assign(targets=[ast.Name(id=name)], value=value):
      variables[name] = _interpret_expr(value, variables)
      return

    case other:
      raise InterpreterError("Syntax not supported", other)

def _interpret_expr(expr: ast.expr, variables: dict) -> Any:
  match expr:
    case ast.BinOp(left=left_ast, op=op, right=right_ast):
      left = _interpret_expr(left_ast, variables)
      right = _interpret_expr(right_ast, variables)
      return _interpret_binop(left, op, right)

    case ast.Name(id=name):
      return variables[name]

    case ast.Constant(value=(int(value) | float(value))):
      return value

    case other:
      raise InterpreterError("Syntax not supported", other)
    

def _interpret_binop(left: Any, op: ast.operator, right: Any) -> Any:
  match op:
    case ast.Add(): return left + right
    case ast.Sub(): return left - right
    case ast.Mult(): return left * right
    case ast.Div(): return left / right
    case ast.Pow(): return left**right
    case other:
      raise InterpreterError(
        "Operator not supported",
        ast.BinOp(ast.Name("_"), other, ast.Name("_")))

class InterpreterError(Exception):
  def __init__(self, msg: str, code: Optional[ast.AST] = None) -> None:
    super().__init__(msg, code)
    self._msg = msg
    self._code = code

  def __str__(self):
    if self._code:
      return f"{self._msg}: {ast.unparse(self._code)}"
    return self._msg

This can then be used to interpret commands, returning a dictionary with all the variables:

>>> interpret("z = x**2+y**2", {"x": 3, "y": 2})
{'x': 3, 'y': 2, 'z': 13}

While this allows you to interpret the Python code however you want (you control the semantics), you are still limited to Python's syntax. For example, you should use the ** operator for exponentiation, not Python's ^ xor-operator.

If you want your own syntax, then you'll probably have to write your own parser. There are a variety of parsing algorithms and parser generators, but I'm partial to hand-written “recursive descent”. This generally involves writing recursive functions of the form parse(Position) -> Optional[tuple[Position, Value]] that gradually consume the input. I have written an example parser and interpreter using that strategy, and have previously contrasted different parsing approaches in an answer about implementing query languages in a Python program.

🌐
Towards Data Science
towardsdatascience.com › home › latest › how to handle json in python
How to handle JSON in Python | Towards Data Science
January 16, 2025 - The syntax of loads() is pretty trivial. We pass a single parameter most of the time which is the json data itself.
🌐
Quora
quora.com › What-is-pass-by-assignment-in-Python
What is pass-by-assignment in Python? - Quora
Technically, Python uses “pass by assignment.” This is like call-by-value, in that you can do this : [code]>def plus_1(x) : > x=x+1 > >x=5 >plus_1(x) >print x 5 [/code]Here, ...
🌐
LinkedIn
linkedin.com › pulse › pass-assignment-python-what-you-need-know-shrawan-baral
Pass by Assignment in Python: What you need to know
June 20, 2023 - In Python, arguments to a function are passed by assignment. This means that when you call a function, each argument is assigned to a variable in the function's scope.
🌐
Reddit
reddit.com › r/learnpython › is it possible to pass a json object(or a python dict) as a command line argument in scrapy?
r/learnpython on Reddit: Is it possible to pass a JSON object(or a Python dict) as a command line argument in Scrapy?
August 27, 2015 -

Hello all,

I hope this is the right place to ask this. I am trying to learn Scrapy and I'm currently trying to pass a JSON Object as an argument so that I can get the urls and XPath selectors and also generate the item class dynamically instead of hardcoding them. I wanted to know if there was any way to do so? I can pass a string argument using the -a flag like

scrapy crawl myspider -a start_urls="url.com" 

but how can I pass a dict? Should I pass a string containing a dict and then convert it back to a dict in my Python code? Or is there a better way? Thanks for your help!

🌐
Reddit
reddit.com › r/learnpython › how is python pass by reference different from the original "pass by reference" concapt?
r/learnpython on Reddit: How is python pass by reference different from the original "pass by reference" concapt?
February 27, 2022 -

Trying to understand how Python works passing arguments in functions. I've heard that Python's approach is referred to as "pass by assignment" or "pass by object reference".

How does this differ from the more traditional "pass by reference" approach? Hopefully someone can explain it in a way that's easy to understand.

🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
August 20, 2025 - Alternatively, you can download hello_frieda.json in the materials by clicking the link below: Free Bonus: Click here to download the free sample code that shows you how to work with JSON data in Python. When you pass in hello_frieda.json to json.tool, then you can pretty print the content of the JSON file in your terminal.
🌐
Python
docs.python.org › 3 › library › json.html
JSON encoder and decoder — Python 3.14.4 documentation
February 23, 2026 - Source code: Lib/json/__init__.py JSON (JavaScript Object Notation), specified by RFC 7159(which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript...