Format JSON output files with indentation

This commit is contained in:
Bob Swift
2021-05-06 07:57:02 -06:00
parent 11da62f93b
commit c09dde4d4a
3 changed files with 19 additions and 3 deletions

View File

@@ -219,15 +219,20 @@ class PicardScript():
new_object._set_new_id()
return new_object
def to_json(self):
def to_json(self, indented=False):
"""Converts the properties of the script object to a JSON formatted string. Note that only property
names listed in `JSON_PROPERTIES` will be included in the output.
Args:
indented (bool): Indent the output.
Returns:
str: The properties of the script object formatted as a JSON string.
"""
items = {key: getattr(self, key) for key in dir(self) if key in self.JSON_OUTPUT}
return json.dumps(items)
if indented:
return json.dumps(items, indent=4, sort_keys=True)
return json.dumps(items, sort_keys=True)
@classmethod
def create_from_json(cls, json_string):

View File

@@ -667,7 +667,7 @@ class ScriptEditorPage(PicardDialog):
filename = name
log.debug('Exporting naming script file: %s' % filename)
if file_type == self.FILE_TYPE_PACKAGE:
script_text = script_item.to_json()
script_text = script_item.to_json(indented=True)
try:
with open(filename, 'w', encoding='utf8') as o_file:
o_file.write(script_text + '\n')

View File

@@ -154,3 +154,14 @@ class ScriptClassesTest(PicardTestCase):
'"version": ""'
'}'
)
self.assertEqual(test_script.to_json(indented=True),
'{\n'
' "author": "Script author",\n'
' "description": "Script description",\n'
' "last_updated": "2021-04-26",\n'
' "license": "",\n'
' "script": "Script text",\n'
' "title": "Script 1",\n'
' "version": ""\n'
'}'
)