Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested JSON #27

Closed
madhavajay opened this issue Sep 21, 2021 · 2 comments
Closed

Nested JSON #27

madhavajay opened this issue Sep 21, 2021 · 2 comments

Comments

@madhavajay
Copy link
Contributor

I have an issue where the output of my cli tool is JSON but then the nested JSON inside the report field is all messed up and it seems I can't properly json.loads the main result. I wonder if there might be a way to detect json and include it properly rather than escaped inside as a substring?

@eshaan7
Copy link
Owner

eshaan7 commented Sep 22, 2021

It's possible to "intercept" the output providing a callback function. See this example.

You should probably be able to write a callback function that does something like:

res: dict = future.result()  # 1. get current result
res["report"] = json.loads(res["report"]) # 2. manipulate report however u want
future._result = res # 3. set new result

@eshaan7
Copy link
Owner

eshaan7 commented Sep 23, 2021

🚨 Important!

Because of #31, I would not recommend using callback functions to modify the future's result anymore. So you are left with 2 other options:

  1. Don't change the behavior on flask-shell2http side, handle the JSON parsing on the client side. Shouldn't be too painful IMO.
  2. Use a decorator to modify the JSON response and return the modified response. See below example:
from flask import make_response, jsonify
import functools

def json_parser_decorator(f):
    @functools.wraps(f)
    def decorator(*args, **kwargs):
        response = f(*args, **kwargs)
        resp_json = response.json.copy()
        resp_json["report"] = json.loads(resp_json["report"])
        return make_response(jsonify(resp_json), response.status_code)
    return decorator

shell2http.register_command(
    endpoint="mytool", command_name="mytool", decorators=[json_parser_decorator]
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants