Intro
Got some Record Tree JSON files from a senior dev. So I quickly
coded up this thing
to make life easier and jot down what I always forget. (Hey, fitting that this is article #256!)
I even used it in PixivDownloader before, but completely blanked on it.
Reading JSON Files
After reading, the returned value changes based on the JSON file structure. It’ll be either a Python list or a dictionary.
| |
Now you can mess with the jsonParse variable.
Lists
If your JSON file looks like this:
| |
Then, jsonParse will be an outer list, with each item inside being a dictionary.
Dictionaries
If your JSON file looks like this:
| |
Then, jsonParse will be a two-level nested dictionary.
Operations
Once you know the type, you just treat it like any Python dictionary or list. For example, given this file:
| |
Code to print 1:
| |
Code to change 4 to 100:
| |
Add an item to make the file look like this:
| |
Basically, just append a dictionary to the list. Here’s the code:
| |
Iteration
For lists, use list iteration:
| |
For dictionaries, use dictionary iteration:
| |
Saving
Use json.dump:
| |
ensure_ascii=False makes sure non-ASCII chars (like Chinese) are written correctly. indent=2 pretty-prints it with 2-space indents.