python tutorial - JSON.DUMP(S) & JSON.LOAD(S) - learn python - python programming
json.dumps() & json.loads()
- In this tutorial, we'll convert Python dictionary to JSON and write it to a text file. Then, we'll read in back from the file and play with it.
Initially we'll construct Python dictionary like this:
The output looks like this:
Now, we want to convert the dictionary to a string using json.dumps:
Output:
- Note that the "json.dumps()" returns a string as indicated by the "s" at the end of "dumps". This process is called encoding.
Let's write it to a file:
Now that the file is written. Let's reads it back and decoding the JSON-encoded string back into a Python dictionary data structure:
- Let's play with the dictionary a little bit.
What's the relative strength of electromagnetic compared to gravity?
Who's the mediator for "strong" force?
- Ok, here is the full code:
If we prefer working with files instead of strings, we may want to use json.dump() / json.load() to encode / decode JSON data: