MCPcopy
hub / github.com/waditu/tushare / encode_string

Method encode_string

tushare/util/demjson.py:4215–4345  ·  view source on GitHub ↗

Encodes a Python string into a JSON string literal.

(self, s, state)

Source from the content-addressed store, hash-verified

4213 return s
4214
4215 def encode_string(self, s, state):
4216 """Encodes a Python string into a JSON string literal.
4217
4218 """
4219 # Must handle instances of UserString specially in order to be
4220 # able to use ord() on it's simulated "characters". Also
4221 # convert Python2 'str' types to unicode strings first.
4222 import unicodedata, sys
4223 import UserString
4224 py2strenc = self.options.py2str_encoding
4225 if isinstance(s, UserString.UserString):
4226 def tochar(c):
4227 c2 = c.data
4228 if py2strenc and not isinstance(c2,unicode):
4229 return c2.decode( py2strenc )
4230 else:
4231 return c2
4232 elif py2strenc and not isinstance(s,unicode):
4233 s = s.decode( py2strenc )
4234 tochar = None
4235 else:
4236 # Could use "lambda c:c", but that is too slow. So we set to None
4237 # and use an explicit if test inside the loop.
4238 tochar = None
4239
4240 chunks = []
4241 chunks.append('"')
4242 revesc = self._rev_escapes
4243 optrevesc = self._optional_rev_escapes
4244 asciiencodable = self._asciiencodable
4245 always_escape = state.options.always_escape_chars
4246 encunicode = state.escape_unicode_test
4247 i = 0
4248 imax = len(s)
4249 while i < imax:
4250 if tochar:
4251 c = tochar(s[i])
4252 else:
4253 c = s[i]
4254 cord = ord(c)
4255 if cord < 256 and asciiencodable[cord] and isinstance(encunicode, bool) \
4256 and not (always_escape and c in always_escape):
4257 # Contiguous runs of plain old printable ASCII can be copied
4258 # directly to the JSON output without worry (unless the user
4259 # has supplied a custom is-encodable function).
4260 j = i
4261 i += 1
4262 while i < imax:
4263 if tochar:
4264 c = tochar(s[i])
4265 else:
4266 c = s[i]
4267 cord = ord(c)
4268 if cord < 256 and asciiencodable[cord] \
4269 and not (always_escape and c in always_escape):
4270 i += 1
4271 else:
4272 break

Callers 6

_do_encodeMethod · 0.95
encode_enumMethod · 0.95
encode_dateMethod · 0.95
encode_datetimeMethod · 0.95
encode_timeMethod · 0.95
encode_timedeltaMethod · 0.95

Calls 4

JSONEncodeErrorClass · 0.85
appendMethod · 0.80
decodeMethod · 0.45

Tested by

no test coverage detected