There are many use cases for converting JSON to a dot notation. For example, my current company used Hue to query our log data. Our logs are stored in JSON, and Hue queries expect a dot notation.
For example, this JSON file
{
"vehicle": {
"car": {
"bmw": true,
"audi": 1,
"ford": "also good"
},
"truck": {
"all": "cool"
}
}
}
Code language: JSON / JSON with Comments (json)
Will look like this, when converted to dot notation:
$.vehicle.car.ford : also good
$.vehicle.car.bmw : True
$.vehicle.car.audi : 1
$.vehicle.truck.all : cool
Code language: JavaScript (javascript)
Note, I am starting everything with $.
because this is how Hue expects it. This part may need to be modify for other use cases.
I wrote the following Python code to convert JSON to dot notation. It will:
- Get data from clipboard
- Convert it to dot notation
- Print converted data
Here is the code:
#! /usr/bin/env python
import json
import pyperclip
def getKeys(val, old="$"):
if isinstance(val, dict):
for k in val.keys():
getKeys(val[k], old + "." + str(k))
elif isinstance(val, list):
for i,k in enumerate(val):
getKeys(k, old + "." + str(i))
else:
print("{} : {}".format(old,str(val)))
data = json.loads(pyperclip.paste())
getKeys(data)
Code language: PHP (php)
It has one external library dependency, which will need to be installed via pip install pyperclip
. I use pyperclip, because it works consistently across different operating systems.
I saved the file as json-to-dot-notation
in my local ~/bin
directory, which is added to my linux PATH. Now I can just copy any JSON, run json-to-dot-notation
and see the data outputted in dot notation.