Home > Software design >  Do we have any function in python/.Net to read complex objects?
Do we have any function in python/.Net to read complex objects?

Time:09-24

I have a nested object and need a function that let you pass in the object and a key and get back the value.

I am not sure which is the best way to even start working that can be used in all cloud provider.

Example Inputs

object = {“a”:{“b”:{“c”:”d”}}}
key = a/b/c
 
object = {“x”:{“y”:{“z”:”a”}}}
key = x/y/z
value = a

CodePudding user response:

If you are working on a Python project, extradict is a 3rdy party library that allows nested access to data structures - it uses "." by defaut, but it would work like this:

In [1]: from extradict import NestedData

In [3]: obj = NestedData({"a":{"b":{"c":"d"}}})

In [4]: key = "a.b.c"

In [5]: obj[key]
Out[5]: 'd'

You can install extradict with pip install extradict. Disclaimer: I am the project author and maintainer

CodePudding user response:

Except for unicode quotation marks, this is just a dictionary in python.

my_object = {"a":{"b":{"c":"d"}}}
print(my_object["a"]["b"]["c"])  # output: d 

If you want to pass the keys in that "a/b/c" format, then write a function to do normal [] access behind the scenes:

def slash_access(obj, keys):
    keys = keys.split("/")
    current = obj
    for key in keys:
        current = current[key]
    return current

my_object = {"a":{"b":{"c":"d"}}}
print(slash_access(my_object, "a/b/c"))

CodePudding user response:

you can unmarshal that json:

import json
input_string = '{"a":{"b":{"c":"d"}}}'
output_dict = json.loads(input_value)

and use output_dict as a dictionary :

output_dict["a"]
output_dict["a"]["b"]["c"]
  • Related