0

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: ')

2 Answers 2

2

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", ...)
Sign up to request clarification or add additional context in comments.

1 Comment

Ah that's how to use the *, thanks
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.