本文整理匯總了Python中simplejson.loads方法的典型用法代碼示例。如果您正苦於以下問題:Python simplejson.loads方法的具體用法?Python simplejson.loads怎麽用?Python simplejson.loads使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類simplejson
的用法示例。
在下文中一共展示了simplejson.loads方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_geojson
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import loads [as 別名]
def get_geojson(self, srid=4326):
geom = json.loads(self.geometry.transform(srid, True).geojson)
if self.feature_type is None:
feature_type = ''
else:
feature_type = self.feature_type.name
properties = {
'id': self.id,
'uri': self.url,
'preferred_name': self.preferred_name,
'feature_type': feature_type,
'admin1': self.admin1,
'admin2': self.admin2
}
return {
'type': 'Feature',
'properties': properties,
'geometry': geom
}
示例2: __init__
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import loads [as 別名]
def __init__(self, cache_file_name=None, update_cache=True, req_timeout=90.0):
"""Establishes basic HTTP params and loads a cache.
Args:
cache_file_name: String file name of cache.
update_cache: Determines whether cache should be written out back to the disk when closing it.
Default is `True`.
req_timeout: Maximum number of seconds to wait without reading a response byte before deciding an error has occurred.
Default is 90.0 seconds.
"""
# TODO - lookup request rate limit
# By observation, ShadowServer can be quite slow, so give it 90 seconds before it times out.
self._requests = MultiRequest(max_requests=2, req_timeout=req_timeout)
# Create an ApiCache if instructed to
self._cache = ApiCache(cache_file_name, update_cache) if cache_file_name else None
示例3: _request_sync
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import loads [as 別名]
def _request_sync(self, request, timeout=5):
global _urllib_request
## Build URL
url = self.getUrl(request)
## Send Request Expecting JSONP Response
response = _urllib_request(url, timeout=timeout)
try:
resp_json = json.loads(response[0])
except ValueError:
return [0, "JSON Error"]
if response[1] != 200 and 'message' in resp_json and 'payload' in resp_json:
return {'message': resp_json['message'],
'payload': resp_json['payload']}
if response[1] == 0:
return [0, resp_json]
return resp_json
示例4: check_for_new_version
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import loads [as 別名]
def check_for_new_version(self):
log.debug("Checking for new version")
request_args = self.form_request_params()
try:
response = post(**request_args)
content = None
content = loads(response.content)
if content is not None and content.get("updateAvailable", False):
new_version = content["message"].replace("New version ", "").replace(" is available!", "")
if new_version > self.__version["current_version"]:
log.info(content["message"])
self.__version["latest_version"] = new_version
log.info("\n\n[===UPDATE===]\n\n New version %s is available! \n\n[===UPDATE===]\n",
self.__version["latest_version"])
except ConnectionRefusedError:
log.warning("Cannot connect to the update service. PLease check your internet connection.")
except Exception as e:
log.exception(e)
示例5: returnFetchContent
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import loads [as 別名]
def returnFetchContent(self, reply):
response = str(reply.readAll())
# qDebug('Response:' + response)
# qDebug('Error: ' + str(reply.error()))
# qDebug('Status: ' + str(reply.rawHeader('Location')))
if reply.rawHeader('Location') == 'http://cartodb.com/noneuser.html' or \
reply.rawHeader('Location') == 'http://carto.com/noneuser.html':
response = '{"error": "User not found"}'
elif reply.error() == QNetworkReply.AuthenticationRequiredError:
response = '{"error": "Confirm user credentials"}'
if self.returnDict:
try:
self.fetchContent.emit(json.loads(response))
except ValueError as e:
qDebug('Error loading json. {}'.format(response))
response = '{"error": "Error loading JSON data"}'
self.fetchContent.emit(json.loads(response))
else:
self.fetchContent.emit(response)
示例6: test_namedtuple_dump
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import loads [as 別名]
def test_namedtuple_dump(self):
for v in [Value(1), Point(1, 2), DuckValue(1), DuckPoint(1, 2)]:
d = v._asdict()
sio = StringIO()
json.dump(v, sio)
self.assertEqual(d, json.loads(sio.getvalue()))
sio = StringIO()
json.dump(v, sio, namedtuple_as_object=True)
self.assertEqual(
d,
json.loads(sio.getvalue()))
sio = StringIO()
json.dump(v, sio, tuple_as_array=False)
self.assertEqual(d, json.loads(sio.getvalue()))
sio = StringIO()
json.dump(v, sio, namedtuple_as_object=True,
tuple_as_array=False)
self.assertEqual(
d,
json.loads(sio.getvalue()))
示例7: test_invalid_escape_sequences
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import loads [as 別名]
def test_invalid_escape_sequences(self):
# incomplete escape sequence
self.assertRaises(json.JSONDecodeError, json.loads, '"\\u')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\u1')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\u12')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\u123')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\u1234')
# invalid escape sequence
self.assertRaises(json.JSONDecodeError, json.loads, '"\\u123x"')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\u12x4"')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\u1x34"')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\ux234"')
if sys.maxunicode > 65535:
# invalid escape sequence for low surrogate
self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u"')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u0"')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u00"')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u000"')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u000x"')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u00x0"')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u0x00"')
self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\ux000"')
示例8: test_object_pairs_hook
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import loads [as 別名]
def test_object_pairs_hook(self):
s = '{"xkd":1, "kcw":2, "art":3, "hxm":4, "qrt":5, "pad":6, "hoy":7}'
p = [("xkd", 1), ("kcw", 2), ("art", 3), ("hxm", 4),
("qrt", 5), ("pad", 6), ("hoy", 7)]
self.assertEqual(json.loads(s), eval(s))
self.assertEqual(json.loads(s, object_pairs_hook=lambda x: x), p)
self.assertEqual(json.load(StringIO(s),
object_pairs_hook=lambda x: x), p)
od = json.loads(s, object_pairs_hook=OrderedDict)
self.assertEqual(od, OrderedDict(p))
self.assertEqual(type(od), OrderedDict)
# the object_pairs_hook takes priority over the object_hook
self.assertEqual(json.loads(s,
object_pairs_hook=OrderedDict,
object_hook=lambda x: None),
OrderedDict(p))
示例9: test_encode_string_conversion
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import loads [as 別名]
def test_encode_string_conversion(self, ensure_ascii):
string_input = "A string \\ / \b \f \n \r \t </script> &"
not_html_encoded = ('"A string \\\\ \\/ \\b \\f \\n '
'\\r \\t <\\/script> &"')
html_encoded = ('"A string \\\\ \\/ \\b \\f \\n \\r \\t '
'\\u003c\\/script\\u003e \\u0026"')
def helper(expected_output, **encode_kwargs):
output = ujson.encode(string_input,
ensure_ascii=ensure_ascii,
**encode_kwargs)
assert output == expected_output
assert string_input == json.loads(output)
assert string_input == ujson.decode(output)
# Default behavior assumes encode_html_chars=False.
helper(not_html_encoded)
# Make sure explicit encode_html_chars=False works.
helper(not_html_encoded, encode_html_chars=False)
# Make sure explicit encode_html_chars=True does the encoding.
helper(html_encoded, encode_html_chars=True)
示例10: revision
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import loads [as 別名]
def revision(request, id, revision):
'''
Get GeoJSON of a place at given revision
'''
place = get_place_or_404(id)
if request.method == 'GET':
revision = Place.objects.revision(place,revision)
geojson = revision['place'].to_geojson()
geojson['version'] = revision['version']
geojson['digest'] = revision['digest']
return render_to_json_response(geojson)
elif request.method == 'PUT':
user_id = request.user.id
username = request.user.username
data = json.loads(request.body)
comment = data.get('comment', '')
metadata = {
'user': username,
'user_id': user_id,
'comment': comment
}
place = place.rollback(revision, metadata=metadata) #FIXME: handle invalid revision ids
return render_to_json_response(place.to_geojson())
else:
return render_to_json_response({'error': 'Method Not Allowed'}, status=405)
示例11: coerce
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import loads [as 別名]
def coerce(self, value, **kwargs):
"""Coerces JSON values properly."""
return json.loads(json.dumps(value))
示例12: _read_cache_from_file
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import loads [as 別名]
def _read_cache_from_file(self):
"""Read the contents of the cache from a file on disk."""
cache = {}
try:
with(open(self._cache_file_name, 'r')) as fp:
contents = fp.read()
cache = simplejson.loads(contents)
except (IOError, JSONDecodeError):
# The file could not be read. This is not a problem if the file does not exist.
pass
return cache
示例13: assert_cache_written
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import loads [as 別名]
def assert_cache_written(mock_write, patched_open):
T.assert_equal(mock_write.call_count, 1)
for call in patched_open.mock_calls:
name, args, kwargs = call
if '().write' != name:
continue
return simplejson.loads(args[0])
return None
示例14: __init__
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import loads [as 別名]
def __init__(self, url):
self.file_dir = os.path.dirname(__file__)
f = open(os.path.join(self.file_dir, 'apps.json'))
data = json.loads(f.read())
f.close()
self.categories = data['categories']
self.apps = data['apps']
self.url = url
示例15: python_value
# 需要導入模塊: import simplejson [as 別名]
# 或者: from simplejson import loads [as 別名]
def python_value(self, value):
if value is not None:
try:
return json.loads(value)
except (TypeError, ValueError):
return value