-1

I have a JSON file with

{
        "t": 5550.45, 
         "r": 12.4
}

Now I would like to have an element with Dv= 1.0e-04*np.exp(-300000.0/r/t)

So my question is can I write Dv as a key value pair like other parameters above?

newstudent
  • 402
  • 6
  • 19
  • 1
    load json, do calculation and write it back – RomanPerekhrest Aug 01 '23 at 11:30
  • The only valid data types in JSON are strings, numbers, booleans, lists, and dictionaries. You could save your expression as a string and calculate it using `eval`, but keep in mind that it isn't secure because it leaves you vulnerable to injection-type attacks if your json comes from an untrusted source, or is otherwise editable – Pranav Hosangadi Aug 01 '23 at 13:27

1 Answers1

0

If you accept that the value of the key is given as a string then you can leverage eval(). Note that this opens you up to an attack given by evil data but technically this is possible. See: Why is using 'eval' a bad practice?

import numpy

data = {
    "t": 5550.45, 
    "r": 12.4,
    "dv": "1.0e-04 * numpy.exp(-300000.0/data['r']/data['t'])"
}
data["dv"] = eval(data["dv"])

print(data)

That will give you:

{'t': 5550.45, 'r': 12.4, 'dv': 1.2793161767043818e-06}

Alternatively, If you control the "json" you could potentially swap that out for a python dictionary. They look very similar. That would allow you to do something like:

import numpy

data = {
    "t": 5550.45, 
    "r": 12.4,
    "dv": lambda d : 1.0e-04 * numpy.exp(-300000.0/d['r']/d['t'])
}
data["dv"] = data["dv"](data)

print(data)
JonSG
  • 10,542
  • 2
  • 25
  • 36