♦ πŸ† 1 min, 🐌 3 min

🐍 Python: JSON

JSON or JavaScript Object Notation is a key, value-type object supported in pretty much any language.

I think JSON is one of the most powerful data structures because of it's multidimensionality. Sure databases are more powerful in that aspect, but they are not so simple to use. Plus JSON is in a human-readable format by default, supported in the web browser (in JS) in python, C++ any pretty much any other language.

JSON files are the files that end with .JSON file extension. And yes you can read the file in any text editor.

How JSON file looks like?

An example of a JSON file:

{
"test": {
"a": 1,
"2" : true,
"world is nice": [{"key": "value"}, {"key": "value"}, "a"]
},
"new": 0.5,
"path": "/Users/ziga/desktop",
"this": null
}

You can nest the basic data structures as much as you want. Although you are limited with the amount of the basic data types you can use:

  • dict or JSON object
  • string
  • float
  • array
  • bool
  • int
  • null

One more thing. In the JSON file all strings need to be inside " and not '.

json module

JSON module in python is pretty handy. Full docs here . In this post, we'll look into some of the most frequently used functions.

First, to access the module:

import json

Then we get access to:

  • json.dumps(): method used to convert dict like data structure into str. Needed operation to write to the disk. You can also use json.dump but dumps() performs the conversion to str in one go and is faster than dump.
  • json.dump or json.dump(data, file) will convert JSON in chunks and can be much slower than dumps. It creates a stream of data instead of one str chunk. Handy when writing to a file.

To get the JSON/dict from the str or read from JSON file:

  • json.load: loading from a file
  • json.loads: conversion from str to dict.

read/load JSON file:

Nice code_block for JSON file reading:

import json

def get_json_file_content(file_path: str, file_name: str) -> dict:
with open(f"{file_path}/{file_name}", 'w') as file:
json_data = json.load(file)
return json_data

write/store/create JSON file

Nice code_block for creating JSON files:

import json

def save_json_file(file_path: str, file_name: str, json_file_content: dict) -> None:
with open(f"{file_path}/{file_name}", 'w') as file:
file.write(
json.dumps(
json_file_content,
indent=4
)
)

That's it. This should be enough to get you started with python.

🐍 Python series:

Get notified & read regularly πŸ‘‡