PageRenderTime 54ms CodeModel.GetById 2ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/miscutil/lib/jsonutils.py

https://github.com/chokribr/invenio-1
Python | 102 lines | 55 code | 5 blank | 42 comment | 11 complexity | 47d053a13269175a744a9537f3a3b34e MD5 | raw file
Possible License(s): GPL-2.0
  1. # -*- coding: utf-8 -*-
  2. ##
  3. ## This file is part of Invenio.
  4. ## Copyright (C) 2011, 2012 CERN.
  5. ##
  6. ## Invenio is free software; you can redistribute it and/or
  7. ## modify it under the terms of the GNU General Public License as
  8. ## published by the Free Software Foundation; either version 2 of the
  9. ## License, or (at your option) any later version.
  10. ##
  11. ## Invenio is distributed in the hope that it will be useful, but
  12. ## WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. ## General Public License for more details.
  15. ##
  16. ## You should have received a copy of the GNU General Public License
  17. ## along with Invenio; if not, write to the Free Software Foundation, Inc.,
  18. ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
  19. """JSON utilities."""
  20. import re
  21. import sys
  22. if sys.hexversion < 0x2060000:
  23. try:
  24. import simplejson as json
  25. CFG_JSON_AVAILABLE = True
  26. except ImportError:
  27. # Okay, no Ajax app will be possible, but continue anyway,
  28. # since this package is only recommended, not mandatory.
  29. CFG_JSON_AVAILABLE = False
  30. json = None
  31. else:
  32. import json
  33. CFG_JSON_AVAILABLE = True
  34. def json_unicode_to_utf8(data):
  35. """Change all strings in a JSON structure to UTF-8."""
  36. if type(data) == unicode:
  37. return data.encode('utf-8')
  38. elif type(data) == dict:
  39. newdict = {}
  40. for key in data:
  41. newdict[json_unicode_to_utf8(key)] = json_unicode_to_utf8(data[key])
  42. return newdict
  43. elif type(data) == list:
  44. return [json_unicode_to_utf8(elem) for elem in data]
  45. else:
  46. return data
  47. def json_decode_file(filename):
  48. """
  49. Parses a textfile using json to build a python object representation
  50. """
  51. seq = open(filename).read()
  52. ## The JSON standard has no comments syntax. We have to remove them
  53. ## before feeding python's JSON parser
  54. seq = json_remove_comments(seq)
  55. ## Parse all the unicode stuff to utf-8
  56. return json_unicode_to_utf8(json.loads(seq))
  57. def json_remove_comments(text):
  58. """ Removes C style comments from the given string. Will keep newline
  59. characters intact. This way parsing errors from json will point to the
  60. right line.
  61. This is primarily used to make comments in JSON files possible.
  62. The JSON standard has no comments syntax, but we want to use
  63. JSON for our profiles and configuration files. The comments need to be
  64. removed first, before the text can be feed to the JSON parser of python.
  65. @param text: JSON string that should be cleaned
  66. @type text: string
  67. @return: Cleaned JSON
  68. @rtype: string
  69. """
  70. def replacer(match):
  71. s = match.group(0)
  72. if s.startswith('/'):
  73. return ""
  74. else:
  75. return s
  76. pattern = re.compile(
  77. r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"',
  78. re.DOTALL | re.MULTILINE
  79. )
  80. return re.sub(pattern, replacer, text)
  81. def wash_for_js(text):
  82. """
  83. DEPRECATED: use htmlutils.escape_javascript_string() instead,
  84. and take note that returned value is no longer enclosed into
  85. quotes.
  86. """
  87. from invenio.htmlutils import escape_javascript_string
  88. if isinstance(text, basestring):
  89. return '"%s"' % escape_javascript_string(text,
  90. escape_for_html=False,
  91. escape_CDATA=False,
  92. escape_script_tag_with_quote=None)
  93. else:
  94. return text