jsontools.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import datetime
  2. from flask_appbuilder._compat import as_unicode
  3. def dict_to_json(xcol, ycols, labels, value_columns): # pragma: no cover
  4. """
  5. Converts a list of dicts from datamodel query results
  6. to google chart json data.
  7. :param xcol:
  8. The name of a string column to be used has X axis on chart
  9. :param ycols:
  10. A list with the names of series cols, that can be used as numeric
  11. :param labels:
  12. A dict with the columns labels.
  13. :param value_columns:
  14. A list of dicts with the values to convert
  15. """
  16. json_data = dict()
  17. json_data["cols"] = [
  18. {"id": xcol, "label": as_unicode(labels[xcol]), "type": "string"}
  19. ]
  20. for ycol in ycols:
  21. json_data["cols"].append(
  22. {"id": ycol, "label": as_unicode(labels[ycol]), "type": "number"}
  23. )
  24. json_data["rows"] = []
  25. for value in value_columns:
  26. row = {"c": []}
  27. if isinstance(value[xcol], datetime.date):
  28. row["c"].append({"v": (str(value[xcol]))})
  29. else:
  30. row["c"].append({"v": (value[xcol])})
  31. for ycol in ycols:
  32. if value[ycol]:
  33. row["c"].append({"v": (value[ycol])})
  34. else:
  35. row["c"].append({"v": 0})
  36. json_data["rows"].append(row)
  37. return json_data