Home > front end >  Python how to pass JSON objects to a function?
Python how to pass JSON objects to a function?

Time:06-21

I'm parsing a json file that looks like: my_json:

  "DataChangedEntry": {
    "CurrentValue": {
      "RefId": {
        "Value": "aaaaaaa"

So to get "Value" it looks like:

my_json["DataChangedEntry"]["CurrentValue"]["RefId"]["Value"]

I want to send it to a try/except function (because I have a lot of fields to get) but I don't know how to send the json object over. I've tried:

get_value = my_function(my_json, ["DataChangedEntry"]["CurrentValue"]["RefId"]["Value"])

But I get error:

TypeError: list indices must be integers or slices, not str

The my_function is just

def my_function(json_prefix, json_field):
    try:
        value = json_prefix[json_field]
        return value
    except:
        logging.exception('Exception: ')

CodePudding user response:

You have to pass each key as a separate argument (or as a list of separate arguments).

def my_function(obj, *fields):
    for f in fields:
        try:
            obj = obj[f]
        except KeyError:
            logging.exception("Exceptoin: ")
            return
    return obj

my_function(my_json, "DataChangedEntry", "CurrentValue", ...)

CodePudding user response:

I confess that this idea of sending this data separately to a function is quite different.

But to directly return the value aaaaaaa:

  1. Send the first argument as the JSON object value
  2. Send the second argument as the JSON object name string
  3. Send third argument as key list

Then you can use eval() to convert the union of strings into code:

def my_function(json_full, json_prefix, json_field):
    my_json = json_full
    my_json_str = json_prefix
    key_field = '["'   '"]["'.join(json_field)   '"]'
    try:
        value = eval(f'{json_prefix}{key_field}')
        return value
    except Exception as e:
        return e

def main():
    my_json = {
    "DataChangedEntry": {
            "CurrentValue": {
                "RefId": {
                    "Value": "aaaaaaa"
                },
            },
        },
    }

    get_value = my_function(my_json, 'my_json', ["DataChangedEntry","CurrentValue","RefId","Value"])
    print(get_value)

if __name__ == "__main__":
    main()

Output:

aaaaaaa
  • Related