Showing posts with label recursion. Show all posts
Showing posts with label recursion. Show all posts

Monday, 9 January 2017

JSON: Full paths from root node to leaf node

Json Full Paths From Root Node to Leaf

Json Full Paths From Root Node to Leaf

2020-03-16T22:09:29Z



Introduction:

Often there is a requirement to create full paths from root node to leaf node in JSON file. Following python program will generate these paths.

Sample JSON file sample_json_file.json is below:

{
   "data": [
      {
         "id": "X999_Y999",
         "from": {
            "name": "Tom Brady", "id": "X12"
         },
         "message": "Looking forward to 2010!",
         "actions": [
            {
               "name": "Comment",
               "link": "http://www.facebook.com/X999/posts/Y999"
            },
            {
               "name": "Like",
               "link": "http://www.facebook.com/X999/posts/Y999"
            }
         ],
         "type": "status",
         "created_time": "2010-08-02T21:27:44+0000",
         "updated_time": "2010-08-02T21:27:44+0000"
      },
      {
         "id": "X998_Y998",
         "from": {
            "name": "Peyton Manning", "id": "X18"
         },
         "message": "Where's my contract?",
         "actions": [
            {
               "name": "Comment",
               "link": "http://www.facebook.com/X998/posts/Y998"
            },
            {
               "name": "Like",
               "link": "http://www.facebook.com/X998/posts/Y998"
            }
         ],
         "type": "status",
         "created_time": "2010-08-02T21:27:44+0000",
         "updated_time": "2010-08-02T21:27:44+0000"
      }
   ],
  "name": "Anonymous",
  "job": { "hobbyjob": [ "Gardening", "InteriorDesign"], "Fulltimejob": "Lawyer" }
}

Python program to create full paths from above JSON file

#! /usr/bin/env python

# This programm will create paths from root nodes to leafnodes along with values from any json file or structure.

import json
import pprint


json_data = open('sample_json_file.json', 'r').read()
json_dict = json.loads(json_data)

stack = []
final_dict = {}

def do_walk(datadict):

    if isinstance(datadict, dict):
        for key, value in datadict.items():
            stack.append(key)
            #print("/".join(stack))
            if isinstance(value, dict) and len(value.keys()) == 0:
                final_dict["/".join(stack)] = "EMPTY_DICT"
            if isinstance(value, list) and len(value) == 0:
                final_dict["/".join(stack)] = 'EMPTY_LIST'
            if isinstance(value, dict):
                do_walk(value)
            if isinstance(value, list):
                do_walk(value)
            if isinstance(value, unicode):
                final_dict["/".join(stack)] = value
            stack.pop()

    if isinstance(datadict, list):
        n = 0
        for key in datadict:
            stack.append(str(n))
            n = n + 1
            if isinstance(key, dict):
                do_walk(key)
            if isinstance(key, list):
                do_walk(key)
            if isinstance(key, unicode):
                final_dict["/".join(stack)] = key
            stack.pop()


do_walk(json_dict)
pprint.pprint(final_dict)

Below is the result:

# python create_json_paths.py
{u'data/0/actions/0/link': u'http://www.facebook.com/X999/posts/Y999',
 u'data/0/actions/0/name': u'Comment',
 u'data/0/actions/1/link': u'http://www.facebook.com/X999/posts/Y999',
 u'data/0/actions/1/name': u'Like',
 u'data/0/created_time': u'2010-08-02T21:27:44+0000',
 u'data/0/from/id': u'X12',
 u'data/0/from/name': u'Tom Brady',
 u'data/0/id': u'X999_Y999',
 u'data/0/message': u'Looking forward to 2010!',
 u'data/0/type': u'status',
 u'data/0/updated_time': u'2010-08-02T21:27:44+0000',
 u'data/1/actions/0/link': u'http://www.facebook.com/X998/posts/Y998',
 u'data/1/actions/0/name': u'Comment',
 u'data/1/actions/1/link': u'http://www.facebook.com/X998/posts/Y998',
 u'data/1/actions/1/name': u'Like',
 u'data/1/created_time': u'2010-08-02T21:27:44+0000',
 u'data/1/from/id': u'X18',
 u'data/1/from/name': u'Peyton Manning',
 u'data/1/id': u'X998_Y998',
 u'data/1/message': u"Where's my contract?",
 u'data/1/type': u'status',
 u'data/1/updated_time': u'2010-08-02T21:27:44+0000',
 u'job/Fulltimejob': u'Lawyer',
 u'job/hobbyjob/0': u'Gardening',
 u'job/hobbyjob/1': u'InteriorDesign',
 u'name': u'Anonymous'}

Wednesday, 13 March 2002

Recursive functions (using C)

#include
int npower(int m,int n);
int fact(int x);
void reverse(char str[], int n);
void stack_reverse(char str[],int n);
int main()
{
    int result;
    char str[9] = "abcdefghi";
    result=npower(2,5);
    printf("npower result=%d\n", result);
    result=fact(5);
    printf("factorial result=%d\n", result);
    reverse(str, 9);
    printf("\n");
    stack_reverse(str, 0);
    printf("\n");
    return 0;
}

int fact(int x)
{
    if(x==0)
        return 1;
    x=x*fact(x-1);
    return x;
}

int npower(int m, int n)
{
    int d;
    if (n==0)
        return 2;
    m=m*npower(m, n-1);

    printf("m=%d\n", m);
    return m;

}
void reverse(char str[], int n)
{
    if (n==-1) return;     //This function prints backward as well as
    char x;               // as well as forward. Forward printing is
    x=str[n];             //done by poping up characters from stack.
    printf("%c", x);
    reverse(str, n-1);
    printf("%c", x);
}
void stack_reverse(char str[],int n)
{
    char x;
    if (n > 9) return;     // backward printing is done by
    x = str[n];           // poping up the characters from stack repeatedy.
    stack_reverse(str, n+1);
    printf("%c", x);
}
Compile and output:
$ gcc recurse.c
$ ./a.out
m=4
m=8
m=16
m=32
m=64
npower result=64
factorial result=120
ihgfedcbaabcdefghi
ihgfedcba