Created On: August 29, 2022, Last Updated On: August 29, 2022

Query Json or Python Dictionary

Public

Query Json or Python Dictionary, Map, Dot Notation

By Ozzie Ghani3 new



Put following code in your home director bin folder , suppose file name is jqb

#!/bin/bash

# echo $#
# echo ${@}
# Parse Args


PROG_NAME=$(basename $0)

usage() {
    echo -e "***  PLEASE ENTER CORRECT VALUES FOR EACH FLAG  ***"
    echo -e "Usage:$PROG_NAME -f <filter node>"
    echo -e "For Example: sh $PROG_NAME -f  employees.0.id"
    echo -e "*** REFERENCE: ***"
    echo -e "          -f:  (filter), json filter"
    exit 1
}

# echo $#

# check if proper number of parameters are provided when script was executed
if [ $# != 2 ]; then
    usage
fi
# echo $*

# check if -e and -k and -n parameters were provided
# if [[ ! "$*" =~ "-f" ]] || [[ ! "$*" =~ "-k" ]]|| [[ ! "$*" =~ "-n" ]] || [[ ! "$*" =~ "-d" ]]
if [[ ! "$*" =~ "-f" ]]
then
        usage
fi

# store parameters in variables
while [ "$#" != "0" ]; do
    case $1 in
        -f) shift; if [ -n "$1" ]; then export filter=$1 && shift; else usage; fi;;
        # -e) shift; if [ -n "$1" ]; then export package_version=$1 && shift; else usage; fi;;
        # -n) shift; if [ -n "$1" ]; then export node_type=$1 && shift; else usage; fi;;
  # -d) shift; if [ -n "$1" ]; then export disk_mounts=$1 && shift; else usage; fi;;
    esac
done

length() {
  # local input=""

  if [[ -p /dev/stdin ]]; then
    input="$(cat -)"
  else
    input="${@}"
  fi

  if [[ "$#" -gt 0 ]]; then
    args="${@}"
  else
    args=""
  fi

  if [[ -z "${input}" ]]; then
    return 1
  fi

  # echo "${#input}"
echo "${input}|${args}"
# echo  "input=${i}; filter=${f}"
}

# r=$(length $*)

IFS=$'|' read -d '' -ra VALUES < <(length $*)
# eval "length $*"

input=${VALUES[0]}
args=${VALUES[1]}
# exit 0
# echo -e "\n\n"
# python -c 'print("Hi")'

# python /Users/osmanghani/bin/a.py "$( tr "\n" ' ' < $r)"
python3 /Users/osmanghani/bin/a.py "${input}" "${filter}"


Put following file wherever but update the path in above file "/Users/osmanghani/bin/a.py "

a.py

import sys
import json
from types import SimpleNamespace

# print(sys.argv)
input = ''.join(sys.argv[1])
filter = sys.argv[2]


data = json.loads(input)



class Map(dict):
    def __init__(self, *args, **kwargs):
        super(Map, self).__init__(*args, **kwargs)
        for arg in args:
            if isinstance(arg, dict):
                for k, v in arg.items():
                    if isinstance(v, dict):
                        v = Map(v)
                    if isinstance(v, list):
                        self.__convert(v)
                    self[k] = v

        if kwargs:
            for k, v in kwargs.items():
                if isinstance(v, dict):
                    v = Map(v)
                elif isinstance(v, list):
                    self.__convert(v)
                self[k] = v

    def __convert(self, v):
        for elem in range(0, len(v)):
            if isinstance(v[elem], dict):
                v[elem] = Map(v[elem])
            elif isinstance(v[elem], list):
                self.__convert(v[elem])

    def __getattr__(self, attr):
        return self.get(attr)

    def __setattr__(self, key, value):
        self.__setitem__(key, value)

    def __setitem__(self, key, value):
        super(Map, self).__setitem__(key, value)
        self.__dict__.update({key: value})

    def __delattr__(self, item):
        self.__delitem__(item)

    def __delitem__(self, key):
        super(Map, self).__delitem__(key)
        del self.__dict__[key]


data = Map(data)


if filter:
    exec(f"print(data.{filter})")
else:
    print(data)


Usage

Osmans-MBP:tmp osmanghani$ curl -s -X GET https://ozzieghani.com/api/v1/empdata/b26e3354b4 -H "Content-Type: application/json"  | jqb -f report[0]
report[0]
b61a03fbad


References

https://stackoverflow.com/questions/73504174/convert-search-string-to-searchable-keys-from-dictionary-in-python

https://stackoverflow.com/questions/2352181/how-to-use-a-dot-to-access-members-of-dictionary