You'll can use string formatting for that.

In your JSON string, replace random_uuid with %s, than do:

payload = payload % random_uuid

Another option is to use json.dumps to create the json:

payload_dict = {
    'id': random_uuid,
    ...
}

payload = json.dumps(payload_dict)
Answer from Tzach on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › how can i replace these json values with variables?
r/learnpython on Reddit: How can I replace these json values with variables?
January 16, 2021 -

I am trying to make a python script which generates json. I know bash but not python.

I know this is easy, but I cannot figure it out. How do I replace these values with variables? I guess I don't how to call a variable like you can like this in bash: $variable

Thanks.

import json

person_json = {
"name": "Fred",
"place": "Melbourne",
"sex": "male",
"remote": { "addr": "Acacia Avenue", "id": "875932875392" },
"local": { "id": "8475974", "office": "Main" }
}
Discussions

Need Python to read JSON, get values, replace vars with values in a 2nd JSON file
Find answers to Need Python to read JSON, get values, replace vars with values in a 2nd JSON file from the expert community at Experts Exchange More on experts-exchange.com
🌐 experts-exchange.com
January 7, 2022
Python Replace String in json output
I am working on an project where I shall get json results with HTTP request and send it to ElasticSiem. For doing this I will have results separated by new line The results I get are in this form > {"logsourcetypename_… More on discuss.python.org
🌐 discuss.python.org
1
0
February 26, 2022
python - Replace a variable in JSON with an item from a list - Stack Overflow
Use the json standard library. Turn your json into a dictionary, modify it, and serialize it back to json. The functions you're interested in are dumps for Dump-String, which converts native python data structures to json strings and loads, for Load-String, which is the inverse. More on stackoverflow.com
🌐 stackoverflow.com
May 19, 2018
Add variable value in a JSON string in Python - Stack Overflow
I am trying add my variable value in the JSON and everytime I add it, it is not showing properly in my JSON string. ... But whenever I am adding it in the above way, it is not working at all. ... You're escaping the inner double quote " in your string. It should be: b"{\"Machine Name\":\""+hostname+"\"}", None, True) In python ... More on stackoverflow.com
🌐 stackoverflow.com
November 3, 2018
🌐
CopyProgramming
copyprogramming.com › howto › replace-string-in-json-string-with-variable
Python: Substitute variable value in JSON string
June 30, 2023 - Use the function "replacement" to substitute the regular expression "regexp" in the string "originalString".
🌐
Python.org
discuss.python.org › python help
Python Replace String in json output - Python Help - Discussions on Python.org
February 26, 2022 - I am working on an project where I shall get json results with HTTP request and send it to ElasticSiem. For doing this I will have results separated by new line The results I get are in this form > {"logsourcetypename_…
Find elsewhere
🌐
Reddit
reddit.com › r/django › how can i substitute values in a json file?
r/django on Reddit: How can I substitute values in a JSON file?
April 26, 2023 -

When working with Slack APIs, it is very common to have huge blocks of JSON to work with. There are places in that JSON that you have to substitute with the values provided by queries in Django.

In my previous project, I maintained these JSON values in Python files and wrote my own substitution. But this time I feel like using JSON files given the project structure, I tried using render_to_string() but it's not very friendly if a user sends text from client/frontend including special characters.

Have you encountered such a problem before? Any other strategy I can try?

🌐
Reddit
reddit.com › r/learnpython › json template with variables
r/learnpython on Reddit: json template with variables
October 13, 2019 -

Hello, New to Python. I have been trying to find how to variablize a json file in a templates directory:

templates
  |
  -- example.json
module.py

module.py loads example.json but where I am stuck is how to use variables, something like Jinja2

Is this even doable? How should I go about this?

Here is what I am looking to do:

{
  "blocks": [
    {
      "type": "section",
      "text": {
        "type": "plain_text",
        "text": {{ my_custom_message }}
      }
    },
    {
      "type": "context",
      "elements": [
        {
          "type": "mrkdwn",
          "text":{{ my_custom_message_2 }}
        }
      ]
    }
  ]
}
🌐
Osnowden
osnowden.com › posts › automate replacing values in json using python
AUTOMATE REPLACING VALUES IN JSON USING PYTHON | Olivia Snowden's Blog
December 22, 2021 - Next, 3 separate for loops are used to replace the keys in the JSON file. The first for loop replaces the keys that are together in a nested block in the JSON file, without being paired with their values. This is the only for loop that uses 2 variables to iterate.
🌐
Reddit
reddit.com › r/learnpython › what's the quickest way to replace json data?
r/learnpython on Reddit: What's the quickest way to replace json data?
December 29, 2021 -

I'm trying to read through documentation, but I haven't found a direct way to do it. So Reddit we go.

I'm trying to replace a list of json data with a dictionary, because it makes it easier to do SimpleNamespace(**d) on everything. I have the dictionary, but how do I replace the data? I never really learned file IO, especially with json data.

🌐
Opis
opis.io › json-schema › 2.x › variables.html
Variables ($vars) | Opis JSON Schema
Go to the JSON Pointers page. ... $vars can act as substitutions/variables in URI templates.
🌐
IQCode
iqcode.com › code › javascript › python-json-replace-string
python json replace string Code Example
October 17, 2021 - with open('file.json', 'r+') as file: content = file.read() file.seek(0) content.replace('string_replaced', 'new_string') file.write(content) ... Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
🌐
GitHub
gist.github.com › mtth › 4f11c25b026e7818588f
JSON encoding with variable expansion · GitHub
September 11, 2015 - JSON encoding with variable expansion · Raw · json_variable.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
ItSolutionstuff
itsolutionstuff.com › post › python-find-and-replace-string-in-json-file-exampleexample.html
Python Find and Replace String in JSON File Example - ItSolutionstuff.com
October 30, 2023 - Here, i will give you a very simple example to search and replace string in file using python script. we will use open() and replace() function to find string and replace in file using python 3. so, let's see the simple example: ... { "id": ...
Top answer
1 of 2
1

You could use the older modulo formatting. Replace the gte field with %s:

json_data_string = "{\"size\":0,\"query\":{\"bool\":{\"must\":[{\"range\":{\"@timestamp\":{\"time_zone\":\"+09:00\",\"gte\":\"%s\",\"lt\":\"2023-01-25T00:00:00.000Z\"}}},{\"term\":{\"serviceid.keyword\":{\"value\":\"430011397\"}}}]}},\"aggs\":{\"by_day\":{\"auto_date_histogram\":{\"field\":\"@timestamp\",\"minimum_interval\":\"minute\"},\"aggs\":{\"agg-type\":{\"terms\":{\"field\":\"nxlogtype.keyword\",\"size\":1000},\"aggs\":{\"my-sub-agg-name\":{\"avg\":{\"field\":\"size\"}}}}}}}}"

Then use % to format the string

for n in range(minutesDiff):
    print(json_data_string % (datetime.strptime(str(d1 + timedelta(minutes=n)),fmt)))
2 of 2
1

Convert the string representation of JSON to a Python dictionary. You can then access the 'gte' and 'lt' values as follows:

json_data_string = "{\"size\":0,\"query\":{\"bool\":{\"must\":[{\"range\":{\"@timestamp\":{\"time_zone\":\"+09:00\",\"gte\":\"2023-01-24T00:00:00.000Z\",\"lt\":\"2023-01-25T00:00:00.000Z\"}}},{\"term\":{\"serviceid.keyword\":{\"value\":\"430011397\"}}}]}},\"aggs\":{\"by_day\":{\"auto_date_histogram\":{\"field\":\"@timestamp\",\"minimum_interval\":\"minute\"},\"aggs\":{\"agg-type\":{\"terms\":{\"field\":\"nxlogtype.keyword\",\"size\":1000},\"aggs\":{\"my-sub-agg-name\":{\"avg\":{\"field\":\"size\"}}}}}}}}"

j = json.loads(json_data_string)

timestamp = j['query']['bool']['must'][0]['range']['@timestamp']

gte = timestamp['gte']
lt = timestamp['lt']

print(gte, lt)

Output:

2023-01-24T00:00:00.000Z 2023-01-25T00:00:00.000Z