use-jsonify

Try in Playground
python-flaskBest PracticeInformational

0

No tags

No CWE or CVE

It is recommended to use flask.json.jsonify() instead of json.dumps() when building route and let Flask handle the serialization/deserialization.

** Learn More **

  • Flask Documentation on jsonify
  • Different between json.dumps() and flask.jsonify()

Ast Rule: function definition


use-jsonify

How to write a rule
function visit(node, filename, code) {

  const checkElement = (element) => {
    if (!element) {
      return;
    }

    if (element.astType === "functioncall") {
      if (element.functionName.value === "dumps" && element.moduleOrObject.value === "json") {
        const error = buildError(element.start.line, element.start.col, element.end.line, element.end.col,
          "do not use json.dumps, use flask.jsonify() instead", "CRITICAL", "SECURITY");
        addError(error);
      }
    }
    if (element.astType === "assignment") {
      checkElement(element.right);
    }
  };


  const isRoute = node.decorators && node.decorators.filter(d => d.name && d.name.value === "app.route").length > 0;
  const useJson = node.context.imports.filter(i => i.astType === "importstatement" && i.packages.filter(p => p.name && p.name.value === "json").length > 0).length > 0;

  if (!useJson) {
    return;
  }
  if (!isRoute) {
    return;
  }
  if (node.content) {
    if (node.content.astType === "sequence") {
      node.content.elements.forEach(e => checkElement(e));
    }
  }
}

error.py

Expected test result: no error

import json

@app.route('/hello')
def hello_world():
	foo = json.dumps(value)
  return foo
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Playground
  • Snippets
  • Cookbooks
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.