How to Substitute Value for a Variable in a Json in Python

How to substitute value for a variable in a json in python?

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)

Replace a variable in JSON with an item from a list

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)

Use python to replace values with a variable?

...and just like that. Added a random # generator to test actual values.

import json
from pprint import pprint
import numpy as np
import random
min = random.uniform(.01,1)
max = random.uniform(5,15)
a = np.array([min,max])
x = np.percentile(a, 25)
y = np.percentile(a, 50)
z = np.percentile(a, 75)
print (x,y,z)
with open('C:/Temp/NEXRAD_PYTHON/new 1.json','r') as f:
data = json.load(f)



with open('C:/Temp/NEXRAD_PYTHON/new 1.json','w') as f:

data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][0]["value"] = min
data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][1]["value"] = x
data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][2]["value"] = y
data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][3]["value"] = z
data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][4]["value"] = max
data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][0]["label"] = "<"+str(round(min,2))
data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][1]["label"] = str(round(x,2))
data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][2]["label"] = str(round(y,2))
data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][3]["label"] = str(round(z,2))
data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["visualVariables"][0]["stops"][4]["label"] = ">"+str(round(max,2))
data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["authoringInfo"]["visualVariables"][0]["minSliderValue"] = round(min,3)
data["operationalLayers"][0]["layerDefinition"]["drawingInfo"]["renderer"]["authoringInfo"]["visualVariables"][0]["maxSliderValue"] = round(max,3)
f.write(json.dumps(data))


f.close()

How to replace values in a JSON dictionary with their respective shell variables in jq?

You need to export the Bash variables to be seen by jq:

export PROJECT1="randomtext1"
export PROJECT2="randomtext2"
export PROJECT4="randomtext3"

Then you can go with:

jq -n 'with_entries((.value | select(startswith("$"))) |= env[.[1:]])'

and get:

{
"host1": "randomtext1",
"host2": "randomtext2",
"host3": "xyz",
"host4": "randomtext3"
}

iteratively replace values in json file

It's generally a bad idea to do string operations on hierarchical/structured data as there may be many cases where you can break the structure. Since you're already parsing your JSON you can extend the decoder to specifically deal with your case during parsing, e.g.:

numeric_vals = [10, 20, 30, 40]  # numeric values to replace in that order

SEARCH = 'variable'
REPLACE = iter(numeric_vals) # turn into an iterator for sequential access

def replace_values(value):
return {k: next(REPLACE) if v == SEARCH else v for k, v in value.items()}

with open('path/to/your.json') as f:
a = json.JSONDecoder(object_hook=replace_values).decode(f.read())

This ensures you're properly parsing your JSON and that it won't replace, for example, a key that happens to be called 'variable'.

Beware, tho, that it will raise an StopIteration exception if there are more "variable" values in the JSON than there are numeric_vals - you can unravel the dict comprehension in replace_values and deal with such case if you expect to encounter such occurrences.

Replacing JSON value in python [closed]

it works for me.

import simplejson as json

str = """{
"main" : "value_to_replace"
}"""
data = json.loads(str)
print data
data["main"] = "test"
print data

Output:

(test)alexandr@alexandr:~/Desktop$ python test.py
{'main': 'value_to_replace'}
{'main': 'test'}


Related Topics



Leave a reply



Submit