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 OverflowYou'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)
Use str.format instead:
payload = '''json={
"": "0",
"credentials": {
"scope": "GLOBAL",
"id": "{0}",
"username": "testuser3",
"password": "bar",
"description": "biz",
"$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"
}
}'''.format(random_uuid)
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" }
}Need Python to read JSON, get values, replace vars with values in a 2nd JSON file
Python Replace String in json output
python - Replace a variable in JSON with an item from a list - Stack Overflow
Add variable value in a JSON string in Python - 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.
For instance
import json
data = json.loads(x)
y = ['cd', 'pid', 'pod']
for obj in data:
if obj['parameter'] == 'PARA':
obj['parameter'] = y.pop()
json_data = json.dumps(data)
There is a standard library json that I think will do what you are wanting.
Specifically you are going to want to read it in using json.loads(x) and after modifying it you will do json.dumps(modified_x)
You're escaping the inner double quote " in your string. It should be:
b"{\"Machine Name\":\""+hostname+"\"}", None, True)
In python you can also use single quotes ' for strings - and you don't need to escape double quotes inside single quoted strings
b'{"Machine Name":"'+hostname+'"}', None, True)
There are two better ways of doing this though. The first is string formatting which inserts a variable into a string:
b'{"Machine Name":"%s"}' % hostname # python 2.x (old way)
b'{{"Machine Name":"{0}"}}'.format(hostname) # python >= 2.6 (new way - note the double braces at the ends)
The next is with the Python JSON module by converting a python dict to a JSON string
>>> hostname = "machineA.host.com"
>>> data = {'Machine Name': hostname}
>>> json.dumps(data)
'{"Machine Name": "machineA.host.com"}'
This is probably the preferred method as it will handle escaping weird characters in your hostname and other fields, ensuring that you have valid JSON at the end.
Is there a reason you're using a bytestring
instead of manipulating the string consider having the data as a python structure and then dump it to json
>>> d = {}
>>> d['Machine Name'] = hostname
>>> json.dumps(d)
'{"Machine Name": "machineA.host.com"}'
You can build the data structure from the JSON string using a dictionary comprehension, like this:
import json
from datetime import datetime
json_string = '''{"Type1":["2015-03-12","2015-04-08"],"Type2":["2015-01-04","2015-03-09","2015-05-25"]}'''
daytypes = {k: [datetime.strptime(x, '%Y-%m-%d').date() for x in v] for k,v in json.loads(json_string).items()}
>>> daytypes
{'Type1': [datetime.date(2015, 3, 12), datetime.date(2015, 4, 8)], 'Type2': [datetime.date(2015, 1, 4), datetime.date(2015, 3, 9), datetime.date(2015, 5, 25)]}
If you must have tuples in your dictionary then you can convert the list into a tuple in the dict comprehension:
daytypes = {k: tuple(datetime.strptime(x, '%Y-%m-%d').date() for x in v) for k,v in json.loads(json_string).items()}
>>> daytypes
{u'Type1': (datetime.date(2015, 3, 12), datetime.date(2015, 4, 8)), u'Type2': (datetime.date(2015, 1, 4), datetime.date(2015, 3, 9), datetime.date(2015, 5, 25))}
You can implement function for serializing:
def toJSON(self):
return json.dumps(self, default=lambda o: o.__dict__,
sort_keys=True, indent=4)
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?
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 }}
}
]
}
]
}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.
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)))
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
The reason your string isn't working is because you used double quotes " for the string instead of single quotes '. Since json format requires double quotes, you only should be using double quotes inside the string itself and then use the single quotes to denote the start/end of a string. (That way you don't need to keep using those \" unnecessarily.
Also, .format() can help with putting variables inside strings to make them easier.
This should fix your json string:
targetTemp = 17
payload = '{\n "nodes": [{\n "attributes": {\n "targetHeatTemperature": {\n "targetValue": {},\n }\n }\n }]\n}'.format(targetTemp)
However, using the json module makes things a lot easier because it allows you to pass in a python dictionary which can be converted from/to a json string.
Example using the json package:
import json
targetTemp = 17
payload = {
"nodes": [{
"attributes": {
"targetHeatTemperature": {
"targetValue": targetTemp
}
}
}]
}
payload_json = json.dumps(payload) # Convert dict to json string
'+ targetTemp +' within the outermost double quotes isn't doing string concatenation. It's literally putting that text.
You should be using "+ targetTemp +"
However, building an actual dictionary, and using json.dumps will be less error-prone