I am trying to write a dynamic program(to parse json files based on their tags) in python and i am using Python exec function to do that. But the program is failing when exec statement is in a function.
RUN 1: Exec in a function:
import json from pandas.io.json import json_normalize import sys def param(dfile): aString = "['widget']['image']~['widget']['window']~['widget']['text']" for nd_part in aString.split('~'): exec("temp = %s%s"%(dfile,nd_part)) print(temp) if __name__ == "__main__": dfile = json.load(open("sample_json.json")) str_list = param(dfile) JSON Data: sample_json.json
{"widget": { "debug": "on", "window": { "title": "Sample Konfabulator Widget", "name": "main_window", "width": 500, "height": 500 }, "image": { "src": "Images/Sun.png", "name": "sun1", "hOffset": 250, "vOffset": 250, "alignment": "center" }, "text": { "data": "Click Here", "size": 36, "style": "bold", "name": "text1", "hOffset": 250, "vOffset": 100, "alignment": "center", "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" } }} Error:
Traceback (most recent call last): File "sample_test_json.py", line 12, in <module> str_list = param(dfile) File "sample_test_json.py", line 9, in param print(temp) NameError: name 'temp' is not defined RUN 2: EXEC in main:
import json from pandas.io.json import json_normalize import sys if __name__ == "__main__": dfile = json.load(open("sample_json.json")) aString = "['widget']['image']~['widget']['window']~['widget']['text']" for nd_part in aString.split('~'): exec("temp = %s%s"%(dfile,nd_part)) print(temp) JSON Data: sample_json.json(same data as above)
Output: No error(Result as expected)
{'hOffset': 250, 'vOffset': 250, 'name': 'sun1', 'alignment': 'center', 'src': 'Images/Sun.png'} {'width': 500, 'height': 500, 'name': 'main_window', 'title': 'Sample Konfabulator Widget'} {'data': 'Click Here', 'hOffset': 250, 'vOffset': 100, 'size': 36, 'style': 'bold', 'onMouseUp': 'sun1.opacity = (sun1.opacity / 100) * 90;', 'name': 'text1', 'alignment': 'center'} RUN 3: I tried eval and tried formatting the string from this post. How to return value from exec in function?
import json from pandas.io.json import json_normalize import sys def param(dfile): aString = "['widget']['image']~['widget']['window']~['widget']['text']" for nd_part in aString.split('~'): exec('temp = "{}""{}"'.format(dfile,nd_part)) print(temp) if __name__ == "__main__": dfile = json.load(open("sample_json.json")) str_list = param(dfile) Error:
Traceback (most recent call last): File "sample_test_json.py", line 12, in <module> str_list = param(dfile) File "sample_test_json.py", line 9, in param print(temp) NameError: name 'temp' is not defined Please help me in identifying the issue. Thanks in advance.
eval()but really, there's no need for that either.exec()