Created
June 2, 2023 07:30
-
-
Save tropis/44122f32ef64ff25d11cd0c38196e889 to your computer and use it in GitHub Desktop.
How to make a JSON reader in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Make a JSON file reader | |
Create reader.py | |
Make a function test_hello() that prints "Hello" | |
Make a function test_goodbye() that prints "Goodbye" | |
At the end of the file make a function main() | |
Main should choose to run either test_hello() or test_goodbye() depending on the command line argument. | |
Run the file with command line argument h: | |
python reader.py h | |
and see Hello | |
Run | |
python reader.py g | |
and see Goodbye | |
You may have to study python command line arguments. | |
Ok that was simple, but that is your testing user interface. | |
Now create file reader.json and put a little json in it to describe your friends. | |
For example: | |
name Bob | |
age 16 | |
hair black | |
name Joe | |
age 17 | |
hair green | |
You can google how to write and read json | |
You can test reader.json at https://jsonviewer.stack.hu/ | |
Next, at the top of reader.py add readjson() | |
This function will: | |
Open the file reader.json | |
Read the contents into a dictionary | |
Return the dictionary | |
You will need to install the json package and use json.loads() | |
Below readjson(), make the function test_view() | |
Inside test_view(), call readjson(), and print the dictionary using json.dumps() | |
Finally, modify main() so it will execute test_view() when you run | |
python reader.py v | |
Future Ideas: | |
Make a json file editor. Create functions to add another person, to just print the | |
names, to print the names alphabetically, to save changes to reader.json | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment