I am trying to access a json file in Choregraphe 2.8 but it is not recognising where it is. I am using NAO6 virtual robot and have imported an external python script to this platform which works fine except reading and opening the json file.
I have this part included in my imported python script:
read_json.py
class JsonData():
def open_json(self):
with open('file.json', encoding = 'utf-8', mode='r') as json_file:
self.json_data = json.load(json_file)
return self.json_data
def get_param(self, parameter):
# open json file to access data
self.open_json()
# get the key values from json file
if parameter == "test":
name = self.json_data["Name"]
return name
I used this video to guide me with importing external python script:
attachment_file.py
#other parts of the code are not included...
def onLoad(self):
self.framemanager = ALProxy("ALFrameManager")
def onInput_onStart(self):
self.folderName = self.framemanager.getBehaviorPath(self.behaviorId) + self.getParameter("File name")
if (self.folderName) not in sys.path:
sys.path.insert(0, self.folderName)
self.onStopped()
def onUnload(self):
if (self.folderName) in sys.path:
sys.path.remove(self.folderName)
I have another python script that is written in a box using Choregraphe tools. when I try to import the read_json.py to read the json file I get this error:
...\choregraphe\...\data\PackageManager\apps\.lastUploadedChoregrapheBehavior\behavior_1/..\read_json.py", line 9, in open_json with open('file.json', encoding = 'utf-8', mode='r') as json_file: IOError: [Errno 2] No such file or directory: 'file.json'
For the onInput_onStart(self) section of the file I am using to import read_json.py is written like this:
def onInput_onStart(self):
import read_json
self.a = read_json.JsonData()
json_data = self.a.show_param("test") #string output
self.tts.say(json_data)
I have searched so much on how to import other files from Choregraphe 2.8 but everything else I tried to access a json file, other than the method above, was giving me the same error.
I would really appreciate if anyone can help me with this.
Many thanks in advance.
By writing:
open('file.json', encoding = 'utf-8', mode='r')
you rely on the Python interpreter's current working directory to find file.json
.
In general in Python, it is recommended that you use absolute paths to avoid such confusion, and make sure you control which file you are trying to read.
In Choregraphe Python boxes, you can find the absolute path to your installed behavior with the following expression:
self.behaviorAbsolutePath()
Say your file.json
is located under the behavior_1
directory of your app, you can get its absolute path with:
os.path.join(self.behaviorAbsolutePath(), 'file.json')
Applied to your case, this is how you could read the file properly:
json_file_path = os.path.join(self.behaviorAbsolutePath(), 'file.json')
with open(json_file_path, encoding = 'utf-8', mode='r') as json_file:
self.json_data = json.load(json_file)