图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.4 KiB

  1. import copy
  2. import re
  3. from ..helpers import nativestr
  4. def bulk_of_jsons(d):
  5. """Replace serialized JSON values with objects in a
  6. bulk array response (list).
  7. """
  8. def _f(b):
  9. for index, item in enumerate(b):
  10. if item is not None:
  11. b[index] = d(item)
  12. return b
  13. return _f
  14. def decode_dict_keys(obj):
  15. """Decode the keys of the given dictionary with utf-8."""
  16. newobj = copy.copy(obj)
  17. for k in obj.keys():
  18. if isinstance(k, bytes):
  19. newobj[k.decode("utf-8")] = newobj[k]
  20. newobj.pop(k)
  21. return newobj
  22. def unstring(obj):
  23. """
  24. Attempt to parse string to native integer formats.
  25. One can't simply call int/float in a try/catch because there is a
  26. semantic difference between (for example) 15.0 and 15.
  27. """
  28. floatreg = "^\\d+.\\d+$"
  29. match = re.findall(floatreg, obj)
  30. if match != []:
  31. return float(match[0])
  32. intreg = "^\\d+$"
  33. match = re.findall(intreg, obj)
  34. if match != []:
  35. return int(match[0])
  36. return obj
  37. def decode_list(b):
  38. """
  39. Given a non-deserializable object, make a best effort to
  40. return a useful set of results.
  41. """
  42. if isinstance(b, list):
  43. return [nativestr(obj) for obj in b]
  44. elif isinstance(b, bytes):
  45. return unstring(nativestr(b))
  46. elif isinstance(b, str):
  47. return unstring(b)
  48. return b