alexkras.com

  • Home
  • Top Posts
  • Resume
  • Projects
  • YouTube
  • Boots to Bytes
  • About
  • Contact

Convert JSON to dot notation with Python

December 20, 2017 by Alex Kras Leave a Comment

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"
        }
    }
}

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

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:

  1. Get data from clipboard
  2. Convert it to dot notation
  3. 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)

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.

Filed Under: Python, Tools

I work for Evernote and we are hiring!

Subscribe to this Blog via Email

New posts only. No other messages will be sent.

You can find me on LinkedIn, GitHub, Twitter or Facebook.

This blog is moving to techtldr.com

Leave a Reply Cancel reply

Copyright © 2021 · eleven40 Pro Theme on Genesis Framework · WordPress · Log in