β¦ π 1 min, π 3 min
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.JSON
file looks like?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
objectstring
float
array
bool
int
null
JSON
file all strings need to be inside "
and not '
.json
moduleJSON
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.JSON
/dict
from the str
or read from JSON
file:json.load
: loading from a filejson.loads
: conversion from str
to dict
.JSON
file: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
JSON
filecode_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 π