diff --git a/documents/references.md b/documents/references.md index abdbef9a6ccf026494a00616a3ea6dec3acee12f..3dff948ba786ac59b2d611e24fff0eb0155c55a9 100644 --- a/documents/references.md +++ b/documents/references.md @@ -17,6 +17,9 @@ Used to move to the "Script's Directory", regardless of where the script was lau ### Using Heapq as a Max Heap (Default Behavior is Min Heap) <https://stackoverflow.com/a/48255910> +### Reading/Parsing JSON File with Python +<https://linuxconfig.org/how-to-parse-data-from-json-into-python> + ## Older Relevant References References linked in previous assignments. diff --git a/example_item_set_1.json b/example_item_set_1.json new file mode 100644 index 0000000000000000000000000000000000000000..15c44b79b90055793f41c85e21ed46de3ab353e9 --- /dev/null +++ b/example_item_set_1.json @@ -0,0 +1,22 @@ +[ +{ + "benefit": 12, + "cost": 4 +}, +{ + "benefit": 32, + "cost": 8 +}, +{ + "benefit": 40, + "cost": 2 +}, +{ + "benefit": 30, + "cost": 6 +}, +{ + "benefit": 50, + "cost": 1 +} +] diff --git a/example_item_set_2.json b/example_item_set_2.json new file mode 100644 index 0000000000000000000000000000000000000000..da6bad2659825ba967e81a6f4432a8120a5b9de1 --- /dev/null +++ b/example_item_set_2.json @@ -0,0 +1,14 @@ +[ +{ + "benefit": 35, + "cost": 3 +}, +{ + "benefit": 20, + "cost": 2 +}, +{ + "benefit": 20, + "cost": 2 +} +] diff --git a/resources/interface.py b/resources/interface.py index 53f8178632b85308f772015c1de7551fdc2410c6..6f7040d152809e8c68e34c82180fece0f9c73a6c 100644 --- a/resources/interface.py +++ b/resources/interface.py @@ -9,7 +9,7 @@ User interface for program. """ # System Imports. - +import json # User Class Imports. from resources import logging as init_logging @@ -132,6 +132,7 @@ class UserInterface(): user_input = input() print('') + # Attempt to set user's input as weight. try: user_input = int(user_input.strip()) self._knapsack_algorithm.set_max_weight(user_input) @@ -150,6 +151,26 @@ class UserInterface(): """ Sets "Item Set" value by importing from JSON file. """ + print('Enter a JSON formatted file to import from:') + + # Get user's input. + user_input = input() + print('') + + # Attempt to set file contents as new item set. + with open(user_input, 'r') as file: + # Read in file. + json_data = json.load(file) + + # Check that JSON data is formatted in way we expect. + if self._knapsack_algorithm.validate_item_set(json_data): + # Validated successfully. Set as new item set. + self._knapsack_algorithm.set_item_set(json_data) + print('Successfully set new Item Set from JSON data.') + self._knapsack_algorithm.display_item_set() + else: + # Validation failure. + print('Failed to validate file contents for Item Set.') def add_to_item_Set(self): """